From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../reference/classes/constructor/index.html | 132 +++++ .../ar/web/javascript/reference/classes/index.html | 380 ++++++++++++ .../ar/web/javascript/reference/errors/index.html | 31 + .../reference/errors/unexpected_type/index.html | 68 +++ .../reference/global_objects/array/index.html | 481 +++++++++++++++ .../global_objects/array/isarray/index.html | 146 +++++ .../reference/global_objects/array/join/index.html | 143 +++++ .../reference/global_objects/array/pop/index.html | 134 +++++ .../global_objects/array/reverse/index.html | 124 ++++ .../global_objects/array/slice/index.html | 151 +++++ .../global_objects/date/getdate/index.html | 85 +++ .../reference/global_objects/date/index.html | 261 +++++++++ .../reference/global_objects/date/now/index.html | 80 +++ .../reference/global_objects/date/parse/index.html | 182 ++++++ .../global_objects/date/setdate/index.html | 95 +++ .../reference/global_objects/date/utc/index.html | 133 +++++ .../global_objects/function/call/index.html | 219 +++++++ .../reference/global_objects/function/index.html | 183 ++++++ .../javascript/reference/global_objects/index.html | 126 ++++ .../reference/global_objects/json/index.html | 215 +++++++ .../reference/global_objects/map/index.html | 358 ++++++++++++ .../reference/global_objects/math/index.html | 190 ++++++ .../global_objects/object/constructor/index.html | 152 +++++ .../reference/global_objects/object/index.html | 182 ++++++ .../reference/global_objects/string/index.html | 314 ++++++++++ .../global_objects/string/startswith/index.html | 101 ++++ .../index.html" | 12 + files/ar/web/javascript/reference/index.html | 50 ++ .../operators/destructuring_assignment/index.html | 428 ++++++++++++++ .../web/javascript/reference/operators/index.html | 302 ++++++++++ .../javascript/reference/operators/new/index.html | 178 ++++++ .../operators/object_initializer/index.html | 403 +++++++++++++ .../operators/operator_precedence/index.html | 420 ++++++++++++++ .../javascript/reference/operators/this/index.html | 381 ++++++++++++ .../web/javascript/reference/statements/index.html | 141 +++++ .../reference/statements/return/index.html | 145 +++++ .../get/index.html" | 165 ++++++ .../index.html" | 645 +++++++++++++++++++++ 38 files changed, 7936 insertions(+) create mode 100644 files/ar/web/javascript/reference/classes/constructor/index.html create mode 100644 files/ar/web/javascript/reference/classes/index.html create mode 100644 files/ar/web/javascript/reference/errors/index.html create mode 100644 files/ar/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/map/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/math/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 "files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" create mode 100644 files/ar/web/javascript/reference/index.html create mode 100644 files/ar/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/ar/web/javascript/reference/operators/index.html create mode 100644 files/ar/web/javascript/reference/operators/new/index.html create mode 100644 files/ar/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/ar/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/ar/web/javascript/reference/operators/this/index.html create mode 100644 files/ar/web/javascript/reference/statements/index.html create mode 100644 files/ar/web/javascript/reference/statements/return/index.html create mode 100644 "files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" create mode 100644 "files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" (limited to 'files/ar/web/javascript/reference') diff --git a/files/ar/web/javascript/reference/classes/constructor/index.html b/files/ar/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..135948c80b --- /dev/null +++ b/files/ar/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,132 @@ +--- +title: المنشئ (constructor) +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - جافاسكريبت +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

الـ constructor  هي ميثود خاصة لإنشاء وتهيئة الاوبجكت(كائن) داخل (فئة)class.

+ +
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
+ + + +

بناء الجملة

+ +
constructor([arguments]) { ... }
+ +

الوصف

+ +

يمكننا إستخدام تلك الميثود لمرة واحده فقط ، وفي حال إستخدمنا constructor ﻷكثر من مرة في نفس الفئة الـ class سيحدث {{jsxref("SyntaxError")}} إيرور .

+ +

A constructor can use the super keyword to call the constructor of a parent class.

+ +

إذا لم تحدد ميثود إنشاء سيتم تحديد منشئ بشكل تلقائي.

+ +


+ If you do not specify a constructor method, a default constructor is used.

+ +

أمثلة

+ +

إٍستخدام الميثود (اسلوب) الـconstructor

+ +

ذلك الكود تم أخذه ولصقة من classes sample (live demo)

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Here, it calls the parent class' constructor with lengths
+    // provided for the Polygon's width and height
+    super(length, length);
+    // Note: In derived classes, super() must be called before you
+    // can use 'this'. Leaving this out will cause a reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

مثال آخر

+ +

إنظر إلى ذلك الكود

+ +
class Polygon {
+    constructor() {
+        this.name = "Polygon";
+    }
+}
+
+class Square extends Polygon {
+    constructor() {
+        super();
+    }
+}
+
+class Rectangle {}
+
+Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
+
+console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
+console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
+
+let newInstance = new Square();
+console.log(newInstance.name); //Polygon
+ +

هنا البروتوتيب فئة الـ Square تغيرت ولكن الكونستركتور (المنشئ) مبني على فئة الـPolygon والتي تطلب عندما نقوم بإنشاء حالة مماثلة للـ Square مرة أخرى

+ +

الإنشاء الإفتراضي

+ +

ذكرنا سابقا أنه في حال عدم تحديدك لكونستركتور (منشئ) سيتم تحديد الكونستركتور بشكل إفتراضي ، وبالنسبة للكلاسز (الفئات) الاولية يكون الكونستركتور الخاص بها كما يلي :-

+ +
constructor() {}
+
+ +

أما الفئات المشتقة فتكون بالشكل التالي

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.classes.constructor")}}

+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/classes/index.html b/files/ar/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..d6f0143148 --- /dev/null +++ b/files/ar/web/javascript/reference/classes/index.html @@ -0,0 +1,380 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript 2015 + - Inheritance + - Intermediate + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

+ +

Defining classes

+ +

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

+ +

Class declarations

+ +

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

An important difference between function declarations and class declarations is that function declarations are {{Glossary("Hoisting", "hoisted")}} and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:

+ +
var p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class expressions

+ +

A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) .name property, though)

+ +
// unnamed
+var Rectangle = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle"
+
+// named
+var Rectangle = class Rectangle2 {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle2"
+
+ +

Note: Class expressions also suffer from the same hoisting issues mentioned for Class declarations.

+ +

Class body and method definitions

+ +

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.

+ +

Strict mode

+ +

The bodies of class declarations and class expressions are executed in strict mode i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.

+ +

Constructor

+ +

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a constructor method.

+ +

A constructor can use the super keyword to call the constructor of the super class.

+ +

Prototype methods

+ +

See also method definitions.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+  // Getter
+  get area() {
+    return this.calcArea();
+  }
+  // Method
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+
+const square = new Rectangle(10, 10);
+
+console.log(square.area); // 100
+ +

Static methods

+ +

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

+ +
class Point {
+  constructor(x, y) {
+    this.x = x;
+    this.y = y;
+  }
+
+  static distance(a, b) {
+    const dx = a.x - b.x;
+    const dy = a.y - b.y;
+
+    return Math.hypot(dx, dy);
+  }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+
+console.log(Point.distance(p1, p2)); // 7.0710678118654755
+ +

Boxing with prototype and static methods

+ +

When a static or prototype method is called without a value for this, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class syntax is always executed in strict mode.

+ +
class Animal {
+  speak() {
+    return this;
+  }
+  static eat() {
+    return this;
+  }
+}
+
+let obj = new Animal();
+obj.speak(); // Animal {}
+let speak = obj.speak;
+speak(); // undefined
+
+Animal.eat() // class Animal
+let eat = Animal.eat;
+eat(); // undefined
+ +

If the above is written using traditional function–based syntax, then autoboxing in method calls will happen in non–strict mode based on the initial this value. If the inital value is undefined, this will be set to the global object.

+ +

Autoboxing will not happen in strict mode, the this value remains as passed.

+ +
function Animal() { }
+
+Animal.prototype.speak = function() {
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object
+
+let eat = Animal.eat;
+eat(); // global object
+
+ +

Instance properties

+ +

Instance properties must be defined inside of class methods:

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration:

+ +
Rectangle.staticWidth = 20;
+Rectangle.prototype.prototypeWidth = 25;
+
+ +

 

+ +

Sub classing with extends

+ +

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

If there is a constructor present in subclass, it needs to first call super() before using "this".

+ +

One may also extend traditional function-based "classes":

+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(this.name + ' makes a noise.');
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:

+ +
var Animal = {
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+};
+
+class Dog {
+  constructor(name) {
+    this.name = name;
+  }
+}
+
+// If you do not do this you will get a TypeError when you invoke speak
+Object.setPrototypeOf(Dog.prototype, Animal);
+
+var d = new Dog('Mitzie');
+d.speak(); // Mitzie makes a noise.
+
+ +

Species

+ +

You might want to return {{jsxref("Array")}} objects in your derived array class MyArray. The species pattern lets you override default constructors.

+ +

For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The {{jsxref("Symbol.species")}} symbol lets you do this:

+ +
class MyArray extends Array {
+  // Overwrite species to the parent Array constructor
+  static get [Symbol.species]() { return Array; }
+}
+
+var a = new MyArray(1,2,3);
+var mapped = a.map(x => x * x);
+
+console.log(mapped instanceof MyArray); // false
+console.log(mapped instanceof Array);   // true
+
+ +

Super class calls with super

+ +

The super keyword is used to call corresponding methods of super class.

+ +
class Cat {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Lion extends Cat {
+  speak() {
+    super.speak();
+    console.log(this.name + ' roars.');
+  }
+}
+
+var l = new Lion('Fuzzy');
+l.speak();
+// Fuzzy makes a noise.
+// Fuzzy roars.
+
+
+ +

Mix-ins

+ +

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
var calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.classes")}}

+ +

Running in Scratchpad

+ +

A class can't be redefined. If you're playing with code in Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) and you 'Run' a definition of a class with the same name twice, you'll get a confusing SyntaxError: redeclaration of let <class-name>.

+ +

To re-run a definition, use Scratchpad's menu Execute > Reload and Run.
+ Please vote for bug #1428672.

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/errors/index.html b/files/ar/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/ar/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

+ +

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

+ +

List of errors

+ +

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/errors/unexpected_type/index.html b/files/ar/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..085dc8a167 --- /dev/null +++ b/files/ar/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,68 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - الأخطاء + - جافاسكربت + - نوع الخطأ +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

الرسالة

+ +
TypeError: Unable to get property {x} of undefined or null reference (Edge)
+TypeError: "x" is (not) "y" (Firefox)
+
+Examples:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

نوع الخطأ

+ +

{{jsxref("TypeError")}}.

+ +

 ماذا حصل؟

+ +

خطأ غير متوقع، يحدث كثيرا مع {{jsxref("undefined")}} أو قيم {{jsxref("null")}} .

+ +

أيضا في بعض الوضائف مثل {{jsxref("Object.create()")}} أو {{jsxref("Symbol.keyFor()")}}, تحتاج تقديد أنواع محددة.

+ +

أمثلة

+ +

حالات غير صحيحة

+ +
// undefined and null cases on which the substring method won't work
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Certain methods might require a specific type
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

حل المشكلة

+ +

لإصلاح مؤشر null إلى قيم undefined أو null ، يمكنك استخدام عامل التشغيل typeof ، على سبيل المثال.

+ +
if (typeof foo !== 'undefined') {
+  // الآن نعلم أن القيمة المدخلة غير محددة، نستطيع القيام بأي إجراء بدون خطأ.
+}
+ +

شاهد أيضاً

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/index.html b/files/ar/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..1e00adcf73 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,481 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +
كائن Array في جافاسكربت  هو كائن عام، يستخدم في إنشاء المصفوفات، وهي تشبه قائمة من الكائنات عالية المستوى.
+ +
 
+ +

إنشاء مصفوفة

+ +
var fruits = ["Apple", "Banana"];
+
+console.log(fruits.length);
+// 2
+
+ +

الوصول إلى عنصر محدد في المصفوفة

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

تنفيذ حلقة تكرار على مصفوفة

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

إلحاق عنصر بآخر المصفوفة

+ +
var newLength = fruits.push("Orange");
+// ["Apple", "Banana", "Orange"]
+
+ +

حذف عنصر من نهاية المصفوفة

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

حذف عنصر من بداية المصفوفة

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

إضافة عنصر إلى بداية المصفوفة

+ +
var newLength = fruits.unshift("Strawberry") // add to the front
+// ["Strawberry", "Banana"];
+
+ +

الوصول إلى ترتيب عنصر معينة في المصفوفة

+ +
fruits.push("Mango");
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf("Banana");
+// 1
+
+ +

حذف عنصر عن طريق ترتيبه في المصفوفة

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+// ["Strawberry", "Mango"]
+
+ +

نسخة مصفوفة

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry", "Mango"]
+
+ +

Syntax

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

Parameters

+ +
+
elementN
+
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
+
arrayLength
+
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
+
+ +

الوصف

+ +

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

+ +

Some people think that you shouldn't use an array as an associative array. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

+ +

الوصول إلى عناصر المصفوفة

+ +

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the second element'
+
+ +

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

+ +
console.log(arr.0); // a syntax error
+
+ +

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots on the years object and the following example could be true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['array']);
+
+ +

Relationship between length and numerical properties

+ +

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Increasing the {{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

This is explained further on the {{jsxref("Array.length")}} page.

+ +

Creating an array using the result of a match

+ +

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

The properties and elements returned from this match are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

الخصائص

+ +
+
Array.length
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

الدوال

+ +
+
{{jsxref("Array.from()")}}
+
Creates a new Array instance from an array-like or iterable object.
+
{{jsxref("Array.isArray()")}}
+
Returns true if a variable is an array, if not false.
+
{{jsxref("Array.of()")}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Array instances

+ +

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

الخصائص

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

الدوال

+ +

Mutator methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

+ +
// Assumes Array extras already present (one may use polyfills for these as well)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
+    //   return typeof Array[methodName] === 'function'
+    // });
+    methods = [
+      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
+      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
+      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
+      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
+      'values', 'copyWithin', 'includes'
+    ],
+    methodCount = methods.length,
+    assignArrayGeneric = function(methodName) {
+      if (!Array[methodName]) {
+        var method = Array.prototype[methodName];
+        if (typeof method === 'function') {
+          Array[methodName] = function() {
+            return method.call.apply(method, arguments);
+          };
+        }
+      }
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignArrayGeneric(methods[i]);
+  }
+}());
+
+ +

أمثلة

+ +

إنشاء مصفوفة

+ +

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

إنشاء مصفوفة ذات بعدين

+ +

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

هذه هي النتيجة (الخرج):

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
+ +

التوافق مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/isarray/index.html b/files/ar/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..f78eb1574d --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,146 @@ +--- +title: ()Array.isArray +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

()Array.isArray تفحص القيمة التي تم تمريرها هل هي {{jsxref("Array")}} أم ﻻ.

+ +

بنية الجملة

+ +
Array.isArray(value)
+ +

المعلمات

+ +
+
value
+
القيمة التي سيتم فحصها.
+
+ +

القيمة العائدة

+ +

تكون القيمة العائدة true إذا كانت {{jsxref("Array")}}؛ وتكون false إذا كانت غير ذلك.

+ +

الوصف

+ +

إذا كانت القيمة {{jsxref("Array")}}, true ستكون القيمة العائدة؛ غير ذلك ستكون false.

+ +

لمزيد من التفاصيل، راجع هذا المقال “Determining with absolute accuracy whether or not a JavaScript object is an array” .

+ +

أمثلة

+ +
//true جميع الأمثلة التالية ترجع
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+//هي نفسها مصفوفة Array.prototype حقيقة معروفة أن
+Array.isArray(Array.prototype);
+
+//false جميع الأمثلة التالية ترجع
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+
+ +

Polyfill

+ +

Running the following code before any other code will create Array.isArray() if it's not natively available.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}}
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/join/index.html b/files/ar/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..427509f1ec --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,143 @@ +--- +title: ()Array.prototype.join +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Prototype + - جافاسكربت + - دالة + - دمج Array + - دمج المصفوفات + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

دالة ()join تقوم بدمج جميع عناصر المصفوفة في نص واحد.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+a.join();    // 'Wind,Rain,Fire'
+a.join('-'); // 'Wind-Rain-Fire'
+ +

صيغة الكتابة

+ +
str = arr.join([separator = ','])
+ +

المعاملات

+ +
+
separator
+
اختياري. يحدد النص الذي سيقوم بفصل عناصر المصفوفة عن بعضهم البعض. الـ separator سيتحول إلى جزء من النص الناتج. إذا لم يتم تمريره، سيتم الفصل بين عناصر المصفوفة بالـ comma. إذا كان الـseparator عبارة عن نص فارغ، سيتم ضم عناصر المصفوفة دون أي فاصل
+
+ +

القيمة العائدة

+ +

عناصر المصفوفة مضمومين في هيئة نص.

+ +

الوصف

+ +

تقوم بدمج عناصر المصفوفة في هيئة نص، إذا كان أحد هذه العناصر قيمة فارغة أو غير معرف سيتم تحويله إلى نص فارغ.

+ +

أمثلة

+ +

ضم عناصر المصفوفة بأربعة طرق مختلفة

+ +

المثال التالي يقوم بإنشاء مصفوفة a ، بها ثلاثة عناصر، ثم يقوم بضم هذه العناصر الثلاثة، ثم يقوم بضم هذه العناصر الثلاثة إلى نص واحد بأربعة طرق: استخدام الـ separator الإفتراضي، ثم باستخدام الـ comma والمسافة، ثم باستخدام علامة الجمع وأخيرا باستخدام نص فارغ.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+var myVar1 = a.join();      // myVar1 إلى 'Wind,Rain,Fire' تسند
+var myVar2 = a.join(', ');  // myVar2 إلى 'Wind, Rain, Fire' تسند
+var myVar3 = a.join(' + '); // myVar3 إلى 'Wind + Rain + Fire' تسند
+var myVar4 = a.join('');    // myVar4 إلى 'WindRainFire' تسند
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
الصفةالحالةتعليق
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/pop/index.html b/files/ar/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..247f45fc14 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,134 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+   دالة pop() هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاعه
+ +
 
+ +

Syntax

+ +
arr.pop()
+ +

قيمة الإرجاع

+ +

تعيد أخر عنصر من المصفوفة و تعيد {{jsxref("undefined")}}  في حال  كانت المصفوفة فارغة

+ +

وصف

+ +

 دالة POP هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاع تلك القيمة إلى الطالب 

+ +

pop is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

+ +

 في حالة استدعائك لدالة POP على مصفوفة فارغة فسيتم إرجاع  {{jsxref("undefined")}} 

+ +

أمثلة

+ +

إزالة العنصر الأخير من المصفوفة

+ +

التعليمة البرمجية التالية : تقوم بإنشاء مصفوفة(myFish )   تحتوي على أربعة  عناصر ثم تقوم بمسح أخر عنصر   

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

مواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مواصفاتالحالةتعليق
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/reverse/index.html b/files/ar/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..b179e52bc1 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,124 @@ +--- +title: ()Array.prototype.reverse +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

دالة الـ ()reverse تقوم بعكس ترتيبا عناصر المصفوفة مكانيا، بحيث يصبح العنصر الأول في المصفوفة في آخر المصفوفة، ويكون آخر عنصر فيها في أول المصفوفة.

+ +

صيغة الكتابة

+ +
arr.reverse()
+ +

القيمة العائدة

+ +

المصفوفة المعكوسة.

+ +

الوصف

+ +

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

+ +

أمثلة

+ +

عكس العناصر في مصفوفة

+ +

المثال التالي يقوم بإنشاء مصفوفة myArray تحتوي على ثلاثة عناصر، ثم يوم بعكس المصفوفة.

+ +
var myArray = ['one', 'two', 'three'];
+myArray.reverse();
+
+console.log(myArray) // ['three', 'two', 'one']
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
المواصفةالحالةتعليق
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/slice/index.html b/files/ar/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..c0e4bde2c2 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,151 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - المصفوفات + - جافا سكريبت +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

ال slice() method إرجاع نسخة ضئيلة من جزء من مصفوفة إلى object مصفوفة جديد تم تحديده من start إلى end (end غير مضمنة) بينما start و end تمثلان مؤشر العناصر في هذه المصفوفة. لن يتم تعديل المصفوفة الأصلية.

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

تركيب الجملة

+ +
arr.slice([start[, end]])
+
+ +

المعاملات

+ +
+
start {{optional_inline}}
+
مؤشر ذو أساس صفري يبدأ فيه الاستخراج.
+
يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. slice(-2) يستخرج آخر عنصرين في التسلسل.
+
إذا كانت start غير محددة, تبدأslice من المؤشر 0.
+
إذا كانت start is أكبر من نطاق فهرس التسلسل ، يتم إرجاع صفيف فارغ.
+
end {{optional_inline}}
+
مؤشر ذو أساس صفري قبل أن ينتهي الاستخراج. slice مستخرجات إلى ولا تشمل end. على سبيل المثال, slice(1,4) يستخرج العنصر الثاني من خلال العنصر الرابع (العناصر المفهرسة 1 و 2 و 3).
+
يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. slice(2,-1) يستخرج العنصر الثالث من خلال العنصر الثاني إلى الأخير في التسلسل.
+
إذا تم حذف end, slice مستخرجات من خلال نهاية التسلسل(arr.length).
+
اذا كانت end أكبر من طول التسلسل,  فإنslice تستخرج حتى نهاية التسلسل(arr.length).
+
+ +

القيمة العائدة

+ +

مصفوفة جديدة تحتوي على العناصر المستخرجة.

+ +

الوصف

+ +

slice لا تغير المصفوفة الأصلية. تقوم بإرجاع نسخة ضئيلة من العناصر من المصفوفة الأصلية. يتم نسخ عناصر الصفيف الأصلي في الصفيف الذي تم إرجاعه كما يلي:

+ + + +

إذا تمت إضافة عنصر جديد إلى أي مصفوفة ، فلن تتأثر المصفوفة الآخرى.

+ +

أمثلة

+ +

إعادة جزء من من مصفوفة موجودة

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

باستخدام slice

+ +

في المثال التالي, تقومslice بإنشاء مصفوفة جديدة newCar, من myCar. كلاهما يتضمن إشارة إلى الobject myHonda. عندما يتغير لون myHonda إلى الأرجواني, تعكس كلا المصفوفتان التغيير.

+ +
// Using slice, create newCar from myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Change the color of myHonda.
+myHonda.color = 'purple'
+console.log('The new color of my Honda is ' + myHonda.color)
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+ +

This script writes:

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

Array-like objects

+ +

slice method يمكن أيضًا استدعاؤها لتحويل  Array-like objects / مجموعات إلى مصفوفة جديدة. انت فقط {{jsxref("Function.prototype.bind", "bind")}} the method لل object. The {{jsxref("Functions/arguments", "arguments")}}داخل دالة هو مثال على 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+
+ +

البناء يمكن أن يتم ب {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} ويمكن تقليلها باستخدام [].slice.call(arguments) بدلا منArray.prototype.slice.call.

+ +

على أي حال يمكن تبسيطها باستخدام {{jsxref("Function.prototype.bind", "bind")}}.

+ +
let unboundSlice = Array.prototype.slice
+let slice = Function.prototype.call.bind(unboundSlice)
+
+function list() {
+  return slice(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+ +

المواصفات

+ + + + + + + + + + + + +
مواصفات
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
+ +

التوافق مع المتصفح

+ + + +

{{Compat("javascript.builtins.Array.slice")}}

+ +

انظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/getdate/index.html b/files/ar/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..6a39d68196 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,85 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +tags: + - النموذج المبدئي + - تاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

دالة getDate() تقوم بإرجاع يوم من تاريخ الشهر المحدد وفقاً للوقت المحلي.

+ +
{{EmbedInteractiveExample("pages/js/date-getdate.html")}}
+ + + +

بنية الجملة

+ +
dateObj.getDate()
+
+ +

القيمة العائدة

+ +

رقم صحيح ما بين 1 و31 يمثل يوم محدد من تاريخ الشهر المحدد وفقاً للوقت المحلي.

+ +

أمثلة

+ +

استخدام getDate()

+ +

البيان الثاني قام بتعيين قيمة المتغير day، علي أساس قيمة تاريخ المتغير Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.getDate")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/index.html b/files/ar/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..efaa40ce31 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,261 @@ +--- +title: Date | التاريخ +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

+ +

البنيه

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +
+

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

+
+ +

Parameters

+ +
+

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

+
+ +
+

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

+
+ +
+
value
+
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
+
dateString
+
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+
+
year
+
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
+
month
+
Integer value representing the month, beginning with 0 for January to 11 for December.
+
day
+
Optional. Integer value representing the day of the month.
+
hour
+
Optional. Integer value representing the hour of the day.
+
minute
+
Optional. Integer value representing the minute segment of a time.
+
second
+
Optional. Integer value representing the second segment of a time.
+
millisecond
+
Optional. Integer value representing the millisecond segment of a time.
+
+ +

Description

+ + + +

Properties

+ +
+
{{jsxref("Date.prototype")}}
+
Allows the addition of properties to a JavaScript Date object.
+
Date.length
+
The value of Date.length is 7. This is the number of arguments handled by the constructor.
+
+ +

Methods

+ +
+
{{jsxref("Date.now()")}}
+
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. +
+

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
+
+ +

JavaScript Date instances

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Two digit years map to 1900 - 1999

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Calculating elapsed time

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// using Date objects
+var start = Date.now();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // elapsed time in milliseconds
+
+ +
// using built-in methods
+var start = new Date();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
+
+ +
// to test a function and get back its return
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

+ +

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/ar/web/javascript/reference/global_objects/date/now/index.html b/files/ar/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..ff6379db60 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,80 @@ +--- +title: Date.now() | دالة الوقت الآن +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - التاريخ + - الوقت + - جافاسكربت + - دالة + - دليل + - طريقة بديلة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

تقوم دالة  Date.now() بعرض عدد الثواني التي مضت منذ بداية احتساب الوقت بطريقة Timestamp وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تمامًا (First of January 1970 00:00:00)  بتوقيت UTC.

+ +

بنية الجملة

+ +
var timeInMs = Date.now();
+ +

القيمة الراجعة

+ +

القيمة الراجعة من هذه الدالة ستكون عبارة عن رقم  {{jsxref("Number")}}، هذا الرقم يشير إلى عدد الثواني التي انقضت منذ بداية احتساب الوقت بطريقة TimeStamp بالأنظمة التي تستند إلى UNIX.

+ +

الوصف

+ +

لإن دالة  now() تقوم بإرجاع قيمة ثابتة من الوقت {{jsxref("Date")}} فيجب عليك استخدامها بهذا الشكل   Date.now() .

+ +

طريقة احتياطية (Polyfill)

+ +

تم اعتماد هذه الدالة  في  إصدار ECMA-262 5th المحركات التي لم يتم تحديثها لتدعم هذه الدالة يمكنها أن تحاكي دالة Date.now() عبر استخدام هذه الشيفرة البرمجية، هذه الشيفرة ستسمح للمتصفحات بأن تحاكي وظيفة هذه الدالة في حالة عدم دعمها لها :

+ +
if (!Date.now) { // إذا لم تكن الدالة موجودة
+  Date.now = function now() { // قم بإنشاء الدالة
+    return new Date().getTime(); // واربطها بالوقت الحالي
+  };
+}
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + +
الخاصيةالحالةتعليقات
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.now")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/parse/index.html b/files/ar/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..133b751cd6 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,182 @@ +--- +title: Date.parse() | دالة تحليل الوقت +slug: Web/JavaScript/Reference/Global_Objects/Date/parse +tags: + - Date + - التاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +
{{JSRef}}
+ +

تقوم دالة Date.parse() بتوزيع سلسلة من التاريخ، وإرجاع قيمتها إلي مللي ثانية من بداية تاريخ (1 يناير, 1970, 00:00:00 UTC) إلي التاريخ المحدد داخل الأقواس مثل Date.parse("التاريخ") أو NaN (ليس رقم) إذا كانت السلسلة غير معترف بها (غير صحيحة)، أو في بعض الحالات التي يكون فيها قيم التاريخ غير شرعية (مكتوبة بشكل خاطيء). علي سبيل المثال (2015-02-31).

+ +

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

+ +
{{EmbedInteractiveExample("pages/js/date-parse.html")}}
+ + + +

بنية الجملة

+ +

استدعاء مباشر:

+ +
Date.parse(dateString)
+ +

استدعاء ضمني:

+ +
new Date(dateString)
+ +

المعاملات

+ +
+
dateString
+
النص يمثل RFC2822 أو (a variant of) تاريخ ISO 8601 (قد يتم استخدام تنسيقات أخري، ولكن ربما قد تكون النتائج غير متوقعة).
+
+ +

القيمة الراجعة

+ +

A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, {{jsxref("NaN")}} is returned.

+ +

الوصف

+ +

تقوم دالة parse() بأخذ سلسلة التاريخ مثل ("Des 25, 1995") وتقوم بإرجاع القيمة إلي المللي ثانية منذ بداية احتساب الوقت وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تماماً (First of January 1970 00:00:00)  بتوقيت UTC، حتي الوقت التي قمت بتحديده. وهذه الدالة مفيدة لتعيين قيمة التاريخ استناداً الي قيمة السلسلة، علي سبيل المثال الدمج مع طريقة  {{jsxref("Date.prototype.setTime()", "setTime()")}} و {{jsxref("Global_Objects/Date", "Date")}} .

+ +

Given a string representing a time, parse() returns the time value. It accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g. "Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US time zone abbreviations, but for general use, use a time zone offset, for example, "Mon, 25 Dec 1995 13:30:00 +0430" (4 hours, 30 minutes east of the Greenwich meridian).

+ +

GMT and UTC are considered equivalent. The local time zone is used to interpret arguments in RFC2822 Section 3.3 format that do not contain time zone information.

+ +

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

+ +

ECMAScript 5 دعم تنسيق ISO-8601

+ +

The date time string may be in a simplified ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed. Where the string is ISO 8601 date only, the UTC time zone is used to interpret arguments. If the string is date and time in ISO 8601 format, it will be treated as local.

+ +

While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or NaN.

+ +

Because parse() is a static method of {{jsxref("Date")}}, it is called as Date.parse() rather than as a method of a {{jsxref("Date")}} instance.

+ +

الاختلافات في المنطقة الزمنية المفترضة

+ +

Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore {{jsxref("Date")}} objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

+ +

Fall-back to implementation-specific date formats

+ +

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return {{jsxref("NaN")}}.

+ +

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in {{jsxref("NaN")}}, depending on the browser and values provided, e.g.:

+ +
// سلسلة ليست أيزو مع قيم تاريخ صالحة
+new Date('23/25/2014');
+
+ +

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return {{jsxref("NaN")}} in all browsers compliant with ES5 and later:

+ +
// سلسلة أيزو مع قيمة غير صالحة
+new Date('2014-25-23').toISOString();
+// يُعيد "RangeError: invalid date" في جميع المتصفحات المتوافقة مع es5
+
+ +

SpiderMonkey's implementation-specific heuristic can be found in jsdate.cpp. The string "10 06 2014" is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this rough outline on how the parsing works.

+ +
new Date('10 06 2014');
+
+ +

will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:

+ +
new Date('foo-bar 2014').toString();
+// يُعيد: "Invalid Date" *تاريخ غير صالح*
+
+Date.parse('foo-bar 2014');
+// يُعيد: NaN *ليس رقم*
+
+ +

أمثلة

+ +

استخدام Date.parse()

+ +

إذا كان IPOdate هو كائن {{jsxref("Date")}} موجود، فيمكن تعيينه إلي 9 أغسطس، 1995 (بالتوقيت المحلي) كما يلي:

+ +
IPOdate.setTime(Date.parse('Aug 9, 1995'));
+ +

بعض الأمثلة الأخرى على تحليل سلاسل التاريخ غير القياسية:

+ +
Date.parse('Aug 9, 1995');
+ +

يٌعيد 807937200000 في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');
+ +

يٌعيد 807926400000 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00');
+
+ +

يٌعيد 807937200000 في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');
+
+ +

يٌعيد 0 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00');
+
+ +

يٌعيد 14400000 في المنطقة الزمنية GMT-0400، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');
+
+ +

يٌعيد 14400000 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}{{Spec2('ES5.1')}}Simplified ISO 8601 format added.
{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.parse")}}

+ +

ملاحظات التوافق

+ + + +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/setdate/index.html b/files/ar/web/javascript/reference/global_objects/date/setdate/index.html new file mode 100644 index 0000000000..ca5d89a63e --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/setdate/index.html @@ -0,0 +1,95 @@ +--- +title: Date.prototype.setDate() | دالة تعيين التاريخ +slug: Web/JavaScript/Reference/Global_Objects/Date/setDate +tags: + - التاريخ + - النموذج المبدئي + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setDate +--- +
{{JSRef}}
+ +

دالة setDate() تقوم بتعين يوم من الـ {{jsxref("Date")}} المحدد نسبه إلي الشهر المحدد.

+ +
{{EmbedInteractiveExample("pages/js/date-setdate.html")}}
+ + + +

بنية الجملة

+ +
dateObj.setDate(dayValue [رقم اليوم])
+ +

المعاملات (Parameters)

+ +
+
dayValue
+
يجب أن يكون عدد صحيح يمثل يوم من الشهر. علي سبيل المثال setDate(15) .
+
+ +

القيمة العائدة

+ +

عدد المللي ثانية بين تاريخ 1 يناير 1970 00:00:00 UTC والتاريخ المحدد (يتغير الـ {{jsxref("Date")}} أيضا بتغير المكان [المنطقة الزمنية]).

+ +

الوصف

+ +

إذا كان dayValue [رقم اليوم] خارج نطاق قيم الشهر المحدد لهذا التاريخ، فأن دالة setDate() ستقوم بتحديد الـ {{jsxref("Date")}} [اليوم] وفقاً لذلك. علي سبيل المثال، إذا تم تحديد dayValue [رقم اليوم] إلي 0 فسيتم تعيين التاريخ إلي أخر يوم في الشهر السابق.

+ +

أمثلة

+ +

استخدام setDate()

+ +
var theBigDay = new Date(1962, 6, 7); // 1962-07-07
+theBigDay.setDate(24);  // 1962-07-24
+theBigDay.setDate(32);  // 1962-08-01
+theBigDay.setDate(22);  // 1962-08-22
+theBigDay.setDate(0); // 1962-06-30
+theBigDay.setDate(98); // 1962-10-06
+theBigDay.setDate(-50); // 1962-08-09
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.36', 'Date.prototype.setDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.setDate")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/utc/index.html b/files/ar/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..2d1400af0e --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,133 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - تاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

دالة Date.UTC() تقبل نفس المُعاملات parameters علي الرغم من طول تكوين المنشيء، ويٌعيد التاريخ إلي المللي ثانية من بداية تاريخ 1 يناير, 1970, 00:00:00, التوقيت العالمي.

+ +
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
+ + + +

بنية الجملة

+ +
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

المعاملات (Parameters)

+ +
+
year
+
سنة كاملة.
+
month
+
رقم صحيح ما بين 0 و11 يمثل الشهر.
+
day
+
اختياري. رقم صحيح ما بين 1 و31 يمثل يوم من الشهر.
+
hour
+
اختياري. رقم صحيح ما بين 0 و23 يمثل الساعات.
+
minute
+
اختياري. رقم صحيح ما بين 0 و59 يمثل الدقائق.
+
second
+
اختياري. رقم صحيح ما بين 0 و59 يمثل الثواني.
+
millisecond
+
اختياري. رقم صحيح ما بين 0 و999 يمثل الميلي ثانية.
+
+ +

القيمة العائدة

+ +

رقم يمثل عدد المللي ثانية في التاريخ المحدد منذ 1 يناير, 1970, 00:00:00، التوقيت العالمي.

+ +

الوصف

+ +

تقوم دالة UTC() بأخذ معاملات (parameters) التاريخ المحددة بفاصلة ثم تُعيدها إلي مللي ثانية بين 1 يناير 1970، 00:00:00 التوقيت العالمي، والوقت الذي حددته.

+ +

يجب عليك تحديد السنة كاملة؛ علي سبيل المثال, 1998. إذا كانت السنة محددة ما بين عام 0 و99، تقوم هذه الطريقة بتحويل السنه إلي سنه في القرن العشرين (1900 + سنة)؛ علي سبيل المثال، إذا حددت 95، فسيتم أستخدام 1995.

+ +

تختلف طريقة UTC() عن منشيء التاريخ بطريقتين.

+ + + +

If a parameter you specify is outside of the expected range, the UTC() method updates the other parameters to allow for your number. For example, if you use 15 for month, the year will be incremented by 1 (year + 1), and 3 will be used for the month.

+ +

Because UTC() is a static method of {{jsxref("Date")}}, you always use it as Date.UTC(), rather than as a method of a {{jsxref("Date")}} object you created.

+ +

أمثلة

+ +

استخدام Date.UTC()

+ +

في المثال التالي يقوم بإنشاء التاريخ بإستخدام UTC بدلاً من التوقيت المحلي:

+ +
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.UTC")}}

+ +

ملاحظات التوافق

+ +

Date.UTC with fewer than two arguments

+ +

When providing less than two arguments to Date.UTC, {{jsxref("NaN")}} is returned. This behavior is specified in ECMAScript 2017. Engines who weren't supporting this behavior, have been updated (see {{bug(1050755)}}, ecma-262 #642).

+ +
Date.UTC();
+Date.UTC(1);
+
+// Safari: NaN
+// Chrome/Opera/V8: NaN
+
+// Firefox <54: non-NaN
+// Firefox 54+: NaN
+
+// IE: non-NaN
+// Edge: NaN
+
+ +

اقرأ أيضاً

+ + diff --git a/files/ar/web/javascript/reference/global_objects/function/call/index.html b/files/ar/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..f3c83f04ac --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,219 @@ +--- +title: ()Function.prototype.call +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +
+

تُستدعَى الوظيفة ()call على دالة، أول argument لهذه الوظيفة هو قيمة this الخاصة بالدالة، وال arguments المتبقية (إن وُجدت)، هي  arguments الدالة.

+ +
+

ملاحظة :   صيغة هذه الوظيفة مماثلة تقريبًا  للصيغة الخاصة بـ {{jsxref("Function.prototype.apply", "apply")}} الفرق الوحيد هو ان  ()call تاخذ قائمة من ال arguments  محددة بشكل فردي فيما تاخذ ()apply مصفوفة واحدة من ال arguments.

+
+ +
{{EmbedInteractiveExample("pages/js/function-call.html")}}
+ + + +

صيغة الوظيفة call

+ +
function.call(thisArg, arg1, arg2, ...)
+ +

Parameters

+ +
+
thisArg
+
اختياري. وهو قيمة this المتوفرة في استدعاء الدالة function. لاحظ أن this قد لا تكون القيمة الفعلية التي تراها الوظيفة: اذا كانت هذه الوظيفة دالة في  {{jsxref("Strict_mode", "non-strict mode", "", 1)}} سيتم استبدال  {{jsxref("Global_Objects/null", "null")}} و {{jsxref("Global_Objects/undefined", "undefined")}} بالكائن العام والقيم الاولية ستحول الى كائنات.  
+
...,arg1, arg2
+
 arguments الدالة function.
+
+ +

Return value

+ +

تُرجع نتيجة استدعاء الدالة مع قيمة  this المحددة و ال arguments.

+ +

وصف

+ +

تسمح الوظيفة ()call لدالة او وظيفة خاصة بكائن واحد بان يتم استدعاؤها وتعيينها من قبل كائن مختلف.

+ +

تمنح الوظيفة ()call قيمة this الجديدة الى الدالة/الوظيفة. مع الـ call  يمكنك كتابة الوظيفة مرة واحدة ومن ثم تقوم بتوريثها لكائن آخر دون الحاجة إلى إعادة كتابة الوظيفة للكائن الجديد.

+ +

تحليل الجزء الغامض في الوظيفة ()call

+ +

نظرا لعدم وجود شرح كاف حول هذه الجزئية فقد ارتايت ان اظيف هذه الفقرة التوضيحية لعلها تزيح بعض الغموض عن قيمة ال this التي تمثل ال argument الاول لهذه الوظيفة.

+ +

اذا نظرنا بتمعن في هذا الجزء من داخل الوظيفة call. سنجد ان thisArg ستساوي الكائن العام في حالة undefined او null، والا ستساوي ناتج الكائن Object، تساوي thisArg كائنا في كلتا الحالتين. وعليه فقد اصبحت كائنا، اذن فمن الطبيعي ان تمتلك خصائص. تم تحديد الخاصية _callTemp_ قيمتها this و this تمثل الدالة التي ستستدعى عليها الوظيفة call. واخيرا يتم تنفيذ هذه الدالة:

+ +
Function.prototype.call_like = function( thisArg, args ){
+    thisArg = ( thisArg === undefined || thisArg === null ) ? window : Object( thisArg );
+    thisArg._callTemp_ = this;
+    thisArg._callTemp_();
+}
+ +

في حالة عدم وجود thisArg ستتصرف الدالة fn بشكل طبيعي و this ستساوي الكائن العام:

+ +
var fn = function () {
+    console.log( this ); // [object Window]
+}
+fn.call_like();
+
+
+ +

في حالة وجود thisArg بقيمة اولية ك undefined او null ف this ستساوي ايضا الكائن العام، خلاف ذالك سيتم تمرير قيمتها الى الكائن ()Object، اذا كانت هذه القيمة من القيم الاولية-primitive value سيقوم الكائن بتحويلها الى الكائن المناسب لها، واما اذا كانت هذه القيمة كائنا فلا حاجة لتحويلها و this ستساوي كائنا.

+ +

وهذا يفسر كيف قام الكائن Object بتحويل القيمة الاولية "Youssef belmeskine" الى الكائن String:   

+ +
var fn = function () {
+    console.log( this ); // "Youssef belmeskine"
+    console.log( this === "Youssef belmeskine" ); // false
+    console.log( String(this) === "Youssef belmeskine" ); // true
+}
+fn.call_like( "Youssef belmeskine" );
+
+
+ +

من المهم دائما ذكر المصدر:

+ +
+

بالنسبة لى شخصيا لم اتمكن من فهم هذه الوظيفة وشقيقتها apply بشكل واضح الا عندما قمت بالاطلاع على الكود الداخلى لها. قمت باستخدام هذا الجزء من الكود لتوضيح الفكرة فقط. ستجد ال Polyfill كاملا في هذا الموقع hexmen.com.

+
+ +

أمثلة

+ +

استخدام ال call لِسَلسَلة منشئات الكائن

+ +

تستطيع إستخدام call  لعمل تسلسل لمنشئات-constructors الكائن، وذلك على غرار جافا. في المثال التالي، تم تحديد منشئ الكائن Product مع اثنين من البارامترات name و price. والدالتات Food و Toy  تستدعيان  Product  ممرر لها this و name و price. تقوم Product بتهيئة الخاصيتان name و price فيما تقوم كلا الدالتان المتخصصتان بتحديد ال category.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+var cheese = new Food('feta', 5);
+var fun = new Toy('robot', 40);
+
+ +

إستخدام ال call لإستدعاء الدالة المجهولة الاسم-anonymous function 

+ +

في هذا المثال قمنا بانشاء الدالة المجهولة واستخدمنا call  لإستدعاءها على كل كائن في المصفوفة. الغرض الرئيسي من الدالة المجهولة هو إضافة الدالة print الى كل كائن،  والتي ستكون قادرة على طباعة الفهرس الصحيح لكائنات المصفوفة. تمرير كائن على شكل قيمة this ليس ضروريًا، ولكن تم إنجازه لغرض توضيحي.

+ +
var animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (var i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

استخدام call لاستدعاء دالة وتحديد السياق-context ل   this

+ +

في المثال أدناه، عندما سنقوم باستدعاء greet سترتبط قيمة this  بالكائن obj.

+ +
function greet() {
+  var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+var obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

إستخدام الـcall لاستدعاء دالة وبدون تحديد البرامتر الاول

+ +

في المثال أدناه ،قمنا باستدعاء الدالة display من دون تمرير البرامتر الاول. إذا لم يتم تمرير قيمة this في البرامتر الاول فسترتبط بالكائن العام-global object.

+
+ +
var sData = 'Wisen';
+
+function display(){
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+
+ +
+

تذكر ان قيمة this ستكون  ب undefined في الوضع الصارم. انظر ادناه:

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Function.call")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/function/index.html b/files/ar/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..878d8776b3 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,183 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues similar to {{jsxref("eval")}}. However, unlike eval, the Function constructor allows executing code in the global scope, prompting better programming habits and allower for more efficient code minification.

+ +
{{EmbedInteractiveExample("pages/js/function-constructor.html")}}
+ + + +

Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. However, getting rid of the new operator allows for a smaller minified code size (4 bytes smaller), so it is best to not use new with Function.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own. However, since it is a function itself, it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

Difference between Function constructor and function declaration

+ +

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // this |x| refers global |x|
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // this |x| refers local |x| above
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

The "proper" way to execute external code with Function (for maximum minifyability).

+ +
function makeFunction(code){
+    return Function('"use strict";return ' + code)();
+}
+var add = makeFunction(
+  "" + function(a, b, c){ return a + b + c } // move this to a separate file in the production release
+);
+console.log( add(1, 2, 3) ); // will log six
+ +

Please note that the above code by itself is completely impractical. You should never abuse Function like that. Instead, the above code is meant only to be a simplified example of something like a module loader where there is a base script, then there are hundreads of big optionally loaded modules. Then, instead of the user waiting while they all download, the clients computer only downloads modules as needed so the page loads super fast. Also, it is reccomended that when evaluating many functions, the functions are evaluated together in bulk instead of separatly.

+ +
function bulkMakeFunctions(){
+    var str = "", i = 1, Len = arguments.length;
+    if (Len) {
+        str = arguments[0];
+        while (i !== Len) str += "," + arguments[i], ++i;
+    }
+    return Function('"use strict";return[' + str + ']')();
+}
+const [
+    add,                        sub,                        mul,                        div
+] = bulkMakeFunctions(
+    "function(a,b){return a+b}","function(a,b){return a-b}","function(a,b){return a*b}","function(a,b){return a/b}"
+);
+console.log(sub(add(mul(4,3), div(225,5)), 7))
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/index.html b/files/ar/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..0e46a82c09 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/index.html @@ -0,0 +1,126 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
+ {{jsSidebar("Objects")}}
+

Summary

+

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+
+

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used! Otherwise it returns undefined). The global object itself can be accessed by the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object (including inherited properties, if any).

+

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

+

Standard objects (by category)

+

Value properties

+

Global properties returning a simple value.

+ +

Function properties

+

Global functions returning the result of a specific routine.

+ +

Fundamental objects

+

General language objects, functions and errors.

+ +

Numbers and dates

+

Objects dealing with numbers, dates and mathematical calculations.

+ +

Text processing

+

Objects for manipulating texts.

+ +

Indexed collections

+

Collections ordered by an index. Array-type objects.

+ +

Keyed collections

+

Collections of objects as keys. Elements iterable in insertion order.

+ +

Structured data

+

Data buffers and JavaScript Object Notation.

+ +

Control abstraction objects

+ +

Reflection

+ +

Internationalization

+

Additions to the ECMAScript core for language-sensitive functionalities.

+ +

Other

+ +
+

 

diff --git a/files/ar/web/javascript/reference/global_objects/json/index.html b/files/ar/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..60305cbd07 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,215 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef("Global_Objects", "JSON")}}
+ +

Summary

+

The JSON object contains methods for parsing JavaScript Object Notation ({{glossary("JSON")}}) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

+ +

Description

+ +

JavaScript Object Notation

+

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("null")}}. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + +
JavaScript and JSON differences
JavaScript typeJSON differences
Objects and ArraysProperty names must be double-quoted strings; trailing commas are forbidden.
NumbersLeading zeros are prohibited; a decimal point must be followed by at least one digit.
Strings +

Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

+
+var code = '"\u2028\u2029"';
+JSON.parse(code); // works fine
+eval(code); // fails
+
+
+

The full JSON syntax is as follows:

+
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

+ +

Methods

+
+
{{jsxref("JSON.parse()")}}
+
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
+
{{jsxref("JSON.stringify()")}}
+
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
+
+ +

Polyfill

+

The JSON object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of JSON object in implementations which do not natively support it (like Internet Explorer 6).

+

The following algorithm is an imitation of the native JSON object:

+
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: function(vContent) {
+      if (vContent instanceof Object) {
+        var sOutput = '';
+        if (vContent.constructor === Array) {
+          for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ',', nId++);
+          return '[' + sOutput.substr(0, sOutput.length - 1) + ']';
+        }
+        if (vContent.toString !== Object.prototype.toString) {
+          return '"' + vContent.toString().replace(/"/g, '\\$&') + '"';
+        }
+        for (var sProp in vContent) {
+          sOutput += '"' + sProp.replace(/"/g, '\\$&') + '":' + this.stringify(vContent[sProp]) + ',';
+        }
+        return '{' + sOutput.substr(0, sOutput.length - 1) + '}';
+     }
+     return typeof vContent === 'string' ? '"' + vContent.replace(/"/g, '\\$&') + '"' : String(vContent);
+    }
+  };
+}
+
+

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+
{{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+

Based on Kangax's compat table.

+ +

See also

+ diff --git a/files/ar/web/javascript/reference/global_objects/map/index.html b/files/ar/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..ba5bc93804 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,358 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and {{glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

+ +

Key equality

+ + + +

Objects vs. Maps

+ +

{{jsxref("Object")}} is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Objects have been used as Maps historically.

+ +

However, there are important differences that make Map preferable in certain cases:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MapObject
Accidental KeysA Map does not contain any keys by default. It only contains what is explicitly put into it. +

An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.

+ +
+

Note: As of ES5, this can be bypassed by using {{jsxref("Object.create", "Object.create(null)")}}, but this is seldom done.

+
+
Key TypesA Map's keys can be any value (including functions, objects, or any primitive).The keys of an Object must be either a {{jsxref("String")}} or a {{jsxref("Symbol")}}.
Key Order +

The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion.

+
+

The keys of an Object are not ordered.

+ +
+

Note: Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys. In JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.

+
+
SizeThe number of items in a Map is easily retrieved from its {{jsxref("Map.prototype.size", "size")}} property.The number of items in an Object must be determined manually.
IterationA Map is an iterable, so it can be directly iterated.Iterating over an Object requires obtaining its keys in some fashion and iterating over them.
Performance +

Performs better in scenarios involving frequent additions and removals of key-value pairs.

+
+

Not optimized for frequent additions and removals of key-value pairs.

+
+ +

Setting object properties

+ +

Setting Object properties works for Map objects as well, and can cause considerable confusion.

+ +

Therefore, this appears to work in a way:

+ +
let wrongMap = new Map()
+wrongMap['bla'] = 'blaa'
+wrongMap['bla2'] = 'blaaa2'
+
+console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }
+
+ +

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Othere operations on the data fail:

+ +
wrongMap.has('bla')    // false
+wrongMap.delete('bla') // false
+console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }
+ +

The correct usage for storing data in the Map is through the set(key, value) method.

+ +
let contacts = new Map()
+contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
+contacts.has('Jessie') // true
+contacts.get('Hilary') // undefined
+contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
+contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
+contacts.delete('Raymond') // false
+contacts.delete('Jessie') // true
+console.log(contacts.size) // 1
+
+
+ +

Constructor

+ +
+
{{jsxref("Map/Map", "Map()")}}
+
Creates a new Map object.
+
+ +

Static properties

+ +
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
The constructor function that is used to create derived objects.
+
+ +

Instance properties

+ +
+
{{jsxref("Map.prototype.size")}}
+
Returns the number of key/value pairs in the Map object.
+
+ +

Instance methods

+ +
+
{{jsxref("Map.prototype.clear()")}}
+
Removes all key-value pairs from the Map object.
+
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
+
Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.
+
{{jsxref("Map.prototype.entries()")}}
+
Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.
+
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
+
Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.
+
{{jsxref("Map.get", "Map.prototype.get(key)")}}
+
Returns the value associated to the key, or undefined if there is none.
+
{{jsxref("Map.has", "Map.prototype.has(key)")}}
+
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
+
{{jsxref("Map.prototype.keys()")}}
+
Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
+
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
+
Sets the value for the key in the Map object. Returns the Map object.
+
{{jsxref("Map.prototype.values()")}}
+
Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
+
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
+
Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.
+
+ +

Examples

+ +

Using the Map object

+ +
let myMap = new Map()
+
+let keyString = 'a string'
+let keyObj    = {}
+let keyFunc   = function() {}
+
+// setting the values
+myMap.set(keyString, "value associated with 'a string'")
+myMap.set(keyObj, 'value associated with keyObj')
+myMap.set(keyFunc, 'value associated with keyFunc')
+
+myMap.size              // 3
+
+// getting the values
+myMap.get(keyString)    // "value associated with 'a string'"
+myMap.get(keyObj)       // "value associated with keyObj"
+myMap.get(keyFunc)      // "value associated with keyFunc"
+
+myMap.get('a string')    // "value associated with 'a string'"
+                         // because keyString === 'a string'
+myMap.get({})            // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

Using NaN as Map keys

+ +

{{jsxref("NaN")}} can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:

+ +
let myMap = new Map()
+myMap.set(NaN, 'not a number')
+
+myMap.get(NaN)
+// "not a number"
+
+let otherNaN = Number('foo')
+myMap.get(otherNaN)
+// "not a number"
+
+ +

Iterating Map with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
let myMap = new Map()
+myMap.set(0, 'zero')
+myMap.set(1, 'one')
+
+for (let [key, value] of myMap) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+
+for (let key of myMap.keys()) {
+  console.log(key)
+}
+// 0
+// 1
+
+for (let value of myMap.values()) {
+  console.log(value)
+}
+// zero
+// one
+
+for (let [key, value] of myMap.entries()) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+
+ +

Iterating Map with forEach()

+ +

Maps can be iterated using the {{jsxref("Map.prototype.forEach", "forEach()")}} method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + ' = ' + value)
+})
+// 0 = zero
+// 1 = one
+
+ +

Relation with Array objects

+ +
let kvArray = [['key1', 'value1'], ['key2', 'value2']]
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+let myMap = new Map(kvArray)
+
+myMap.get('key1') // returns "value1"
+
+// Use Array.from() to transform a map into a 2D key-value Array
+console.log(Array.from(myMap)) // Will show you exactly the same Array as kvArray
+
+// A succinct way to do the same, using the spread syntax
+console.log([...myMap])
+
+// Or use the keys() or values() iterators, and convert them to an array
+console.log(Array.from(myMap.keys())) // ["key1", "key2"]
+
+ +

Cloning and merging Maps

+ +

Just like Arrays, Maps can be cloned:

+ +
let original = new Map([
+  [1, 'one']
+])
+
+let clone = new Map(original)
+
+console.log(clone.get(1))       // one
+console.log(original === clone) // false (useful for shallow comparison)
+ +
+

Important: Keep in mind that the data itself is not cloned.

+
+ +

Maps can be merged, maintaining key uniqueness:

+ +
let first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+])
+
+let second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+])
+
+// Merge two maps. The last repeated key wins.
+// Spread operator essentially converts a Map to an Array
+let merged = new Map([...first, ...second])
+
+console.log(merged.get(1)) // uno
+console.log(merged.get(2)) // dos
+console.log(merged.get(3)) // three
+ +

Maps can be merged with Arrays, too:

+ +
let first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+])
+
+let second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+])
+
+// Merge maps with an array. The last repeated key wins.
+let merged = new Map([...first, ...second, [1, 'eins']])
+
+console.log(merged.get(1)) // eins
+console.log(merged.get(2)) // dos
+console.log(merged.get(3)) // three
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Map")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/math/index.html b/files/ar/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..dd3196e0ac --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,190 @@ +--- +title: رياضيات +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

+ +

Description

+ +

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

+ +

Properties

+ +
+
{{jsxref("Math.E")}}
+
Euler's constant and the base of natural logarithms, approximately 2.718.
+
{{jsxref("Math.LN2")}}
+
Natural logarithm of 2, approximately 0.693.
+
{{jsxref("Math.LN10")}}
+
Natural logarithm of 10, approximately 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Base 2 logarithm of E, approximately 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Base 10 logarithm of E, approximately 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Square root of 2, approximately 1.414.
+
+ +

Methods

+ +
+

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of a number.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of a number.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of a number.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of a number.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of a number.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to a number.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of a number.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to a number.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base 10 logarithm of a number.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base 2 logarithm of a number.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base to the exponent power, that is, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of a number rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of a number.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of a number.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of a number.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
Returns the string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integer part of the number x, removing any fractional digits.
+
+ +

Extending the Math object

+ +

As with most of the built-in objects in JavaScript, the Math object can be extended with custom properties and methods. To extend the Math object, you do not use prototype. Instead, you directly extend Math:

+ +
Math.propName = propValue;
+Math.methodName = methodRef;
+ +

For instance, the following example adds a method to the Math object for calculating the greatest common divisor of a list of arguments.

+ +
/* Variadic function -- Returns the greatest common divisor of a list of arguments */
+Math.gcd = function() {
+    if (arguments.length == 2) {
+        if (arguments[1] == 0)
+            return arguments[0];
+        else
+            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
+    } else if (arguments.length > 2) {
+        var result = Math.gcd(arguments[0], arguments[1]);
+        for (var i = 2; i < arguments.length; i++)
+            result = Math.gcd(result, arguments[i]);
+        return result;
+    }
+};
+ +

Try it:

+ +
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/object/constructor/index.html b/files/ar/web/javascript/reference/global_objects/object/constructor/index.html new file mode 100644 index 0000000000..140d95a732 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/object/constructor/index.html @@ -0,0 +1,152 @@ +--- +title: Object.prototype.constructor +slug: Web/JavaScript/Reference/Global_Objects/Object/constructor +translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor +--- +
{{JSRef}}
+ +

بالرجوع إلى {{jsxref("Object")}}constructor ووظيفتها إنشاء حالات من الاوبجكت (الكائن) .نذكرك بأن قيمة الخصائص التي تشير إليها تلك الفانكشان تشير لنفسها ولا تشير إلى سلسة تحتوي على إسم الفانكشان القيمة تقرأ فقط قيم بدائية مثل 1true و "test".

+ +

الوصف

+ +

جميع الاوبجكت ( مع بعض الاستثائات نشأت مع Object.create(null)  ) وستملك وقتها جميعا خاصية الـ constructor . اما  الكائنات المنشأة بدون إستخدام الكونستراكتور بشكل صريح ( مثل  object & array literals )  ستملك أيضا خصائص الكونستركتور بشكل أساسي

+ +
var o = {};
+o.constructor === Object; // true
+
+var o = new Object;
+o.constructor === Object; // true
+
+var a = [];
+a.constructor === Array; // true
+
+var a = new Array;
+a.constructor === Array; // true
+
+var n = new Number(3);
+n.constructor === Number; // true
+
+ +

أمثلة

+ +

عرض الكونستركتور للأوبجكت

+ +

في المثال التالي قمنا بإنشاء بروتوتيب Tree و اوبجكت بإسم theTree  المثال هنا يعرض خصائص الـconstructor للكائن theTree

+ +
function Tree(name) {
+  this.name = name;
+}
+
+var theTree = new Tree('Redwood');
+console.log('theTree.constructor is ' + theTree.constructor);
+
+ +

عندما تقوم بكتابة الكود بعالية  ستحصل على النتيجة الاتية ليوضح لك أكثر  :-

+ +
theTree.constructor is function Tree(name) {
+  this.name = name;
+}
+
+ +

تغير الكونستركتور الخاص بالاوبجكت

+ +

The following example shows how to modify constructor value of generic objects. Only true, 1 and "test" will not be affected as they have read-only native constructors. This example shows that it is not always safe to rely on the constructor property of an object.

+ +
function Type () {}
+
+var types = [
+  new Array(),
+  [],
+  new Boolean(),
+  true,             // remains unchanged
+  new Date(),
+  new Error(),
+  new Function(),
+  function () {},
+  Math,
+  new Number(),
+  1,                // remains unchanged
+  new Object(),
+  {},
+  new RegExp(),
+  /(?:)/,
+  new String(),
+  'test'            // remains unchanged
+];
+
+for (var i = 0; i < types.length; i++) {
+  types[i].constructor = Type;
+  types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()];
+}
+
+console.log(types.join('\n'));
+
+ +

This example displays the following output:

+ +
function Type() {},false,
+function Type() {},false,
+function Type() {},false,false
+function Boolean() {
+    [native code]
+},false,true
+function Type() {},false,Mon Sep 01 2014 16:03:49 GMT+0600
+function Type() {},false,Error
+function Type() {},false,function anonymous() {
+
+}
+function Type() {},false,function () {}
+function Type() {},false,[object Math]
+function Type() {},false,0
+function Number() {
+    [native code]
+},false,1
+function Type() {},false,[object Object]
+function Type() {},false,[object Object]
+function Type() {},false,/(?:)/
+function Type() {},false,/(?:)/
+function Type() {},false,
+function String() {
+    [native code]
+},false,test
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.1', 'Object.prototype.constructor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ESDraft')}} 
+ +

دعم  المتصفحات

+ +
+ + +

{{Compat("javascript.builtins.Object.constructor")}}

+
diff --git a/files/ar/web/javascript/reference/global_objects/object/index.html b/files/ar/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..2eb7c3bb18 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,182 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

The Object constructor creates an object wrapper.

+ +

Syntax

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

Parameters

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
Any value.
+
+ +

Description

+ +

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Methods of the Object constructor

+ +
+
{{jsxref("Object.assign()")}}
+
Copies the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}}
+
Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable string properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property).
+
{{jsxref("Object.values()")}}
+
Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
+
+ +

Object instances and Object prototype object

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Deleting a property from an object

+ +

There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

+ +

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Boolean")}} objects in o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/string/index.html b/files/ar/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..4dd72a6601 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,314 @@ +--- +title: خيط +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

The String global object is a constructor for strings, or a sequence of characters.

+ +

Syntax

+ +

String literals take the forms:

+ +
'string text'
+"string text"
+"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

Strings can also be created using the String global object directly:

+ +
String(thing)
+ +

Parameters

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template literals

+ +

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
+ +
+

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

+
+ +
+
+ +

Long literal strings

+ +

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

+ +

You can use the + operator to append multiple strings together, like this:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Both of these result in identical strings being created.

+ +

Description

+ +

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

+ +

Character access

+ +

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

+ +
return 'cat'[1]; // returns "a"
+
+ +

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

+ +

Comparing strings

+ +

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // true
+  console.log(a + ' is less than ' + b);
+} else if (a > b) {
+  console.log(a + ' is greater than ' + b);
+} else {
+  console.log(a + ' and ' + b + ' are equal.');
+}
+
+ +

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

+ +

Distinction between string primitives and String objects

+ +

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

+ +
var s_prim = 'foo';
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Logs "string"
+console.log(typeof s_obj);  // Logs "object"
+
+ +

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

+ +
var s1 = '2 + 2';             // creates a string primitive
+var s2 = new String('2 + 2'); // creates a String object
+console.log(eval(s1));        // returns the number 4
+console.log(eval(s2));        // returns the string "2 + 2"
+
+ +

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

+ +

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
+ +

Properties

+ +
+
{{jsxref("String.prototype")}}
+
Allows the addition of properties to a String object.
+
+ +

Methods

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Returns a string created by using the specified sequence of Unicode values.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Returns a string created by using the specified sequence of code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Returns a string created from a raw template string.
+
+ +

String generic methods

+ +
+

String generics are non-standard, deprecated and will get removed near future.

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

String instances

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
+ +

Methods

+ +

Methods unrelated to HTML

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
+ +

HTML wrapper methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.String")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/string/startswith/index.html b/files/ar/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..94b059d593 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,101 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +
{{JSRef}}
+ +

startsWith()
+ .طريقة يمكنك تحقق بها إن كان نص يبدء بالعبارة ما و تعيد لك صحيح أو خطأ

+ +
{{EmbedInteractiveExample("pages/js/string-startswith.html")}}
+ + + +

تركيب الجملة | Syntax

+ +
str.startsWith(searchString[, position])
+ +

المعاملات | Parameters

+ +
+
searchString
+
العبارة المبحوث عنها فيالنص.
+
position {{optional_inline}}
+
مكان الذي يبدأ البحث منه فيالنص   الإفتراضي 0
+
+ +

القيمة العائدة | Return value

+ +

العائد يكون صحيح إذا وجد تطابق
+ و إن لم يجيد تطابق يعيد لك خطأ

+ +

الوصف | Description

+ +

هذه الطريقة حساسة إتجاه الحروف
+ case-sensitive

+ +

أمثلة | Examples

+ +

Using startsWith()

+ +
//startswith
+var str = 'To be, or not to be, that is the question.';
+
+console.log(str.startsWith('To be'));         // true
+console.log(str.startsWith('not to be'));     // false
+console.log(str.startsWith('not to be', 10)); // true
+
+ +

Polyfill

+ +

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.startsWith() with the following snippet:

+ +
if (!String.prototype.startsWith) {
+    Object.defineProperty(String.prototype, 'startsWith', {
+        value: function(search, pos) {
+            pos = !pos || pos < 0 ? 0 : +pos;
+            return this.substring(pos, pos + search.length) === search;
+        }
+    });
+}
+
+ +

A more robust (fully ES2015 specification compliant), but less performant and compact, Polyfill is available on GitHub by Mathias Bynens.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ESDraft')}}
+ +

توافق مع متصفحات

+ + + +

{{Compat("javascript.builtins.String.startsWith")}}

+ +

ذات صلة

+ + diff --git "a/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" "b/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" new file mode 100644 index 0000000000..cb667fd3d8 --- /dev/null +++ "b/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" @@ -0,0 +1,12 @@ +--- +title: الارقام في الجافا سكربت +slug: Web/JavaScript/Reference/Global_Objects/الارقام +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +

 وهو كائن غلاف يستخدم لتمثيل ومعالجة الأرقام مثل  37  او 9.25 Numberمنشئ يحتوي على الثوابت وطرق للعمل مع الأرقام. يمكن تحويل قيم الأنواع الأخرى إلى أرقام باستخدام Number()الوظيفة.

+ +

جافا سكريبت رقم نوع عبارة عن قيمة مزدوجة الدقة بتنسيق IEEE 754 تنسيق ثنائي 64 بت ذات ، كما هو الحال doubleفي Java أو C #. هذا يعني أنه يمكن أن يمثل قيمًا كسرية ، ولكن هناك بعض الحدود لما يمكن تخزينه. يحتفظ فقط بحوالي   17 رقم  منزلاً عشريًا من الدقة ؛ الحساب يخضع للتقريب . أكبر قيمة يمكن أن يحملها رقم هي حوالي 1.8 × 10 308 . يتم استبدال الأعداد التي تتجاوز ذلك بثابت الرقم الخاص Infinity.

+ +

الرقم الحرفي مثل 37كود JavaScript هو قيمة فاصلة عائمة ، وليس عددًا صحيحًا. لا يوجد نوع عدد صحيح منفصل في الاستخدام اليومي الشائع. (يحتوي JavaScript الآن على BigIntنوع ، لكنه لم يتم تصميمه ليحل محل Number للاستخدامات اليومية. 37لا يزال رقمًا ، وليس BigInt.)

+ +

يمكن أيضًا التعبير عن الرقم بأشكال حرفية مثل 0b101، 0o13، 0x0A. تعرف على المزيد حول العددي قواعد المعجم هنا .

diff --git a/files/ar/web/javascript/reference/index.html b/files/ar/web/javascript/reference/index.html new file mode 100644 index 0000000000..db41d77223 --- /dev/null +++ b/files/ar/web/javascript/reference/index.html @@ -0,0 +1,50 @@ +--- +title: مرجع جافا سكريبت +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

+ +

Global Objects

+ +

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
+ +

Statements

+ +

This chapter documents all the JavaScript statements and declarations.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Expressions and operators

+ +

This chapter documents all the JavaScript expressions and operators.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Functions

+ +

This chapter documents how to work with JavaScript functions to develop your applications.

+ + + +

Additional reference pages

+ + diff --git a/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..d926351173 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,428 @@ +--- +title: Destructuring assignment +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +
الإسناد بالتفكيك هو تعبير جافاسكربت يجعل من الممكن فك القيم من المصفوفات ( Arrays ) أو الخصائص من الكائنات ( Objects ) إلى متغيرات مميزة.
+ +
+ +
{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html", "taller")}}
+ + + +

Syntax

+ +
let a, b, rest;
+[a, b] = [10, 20];
+console.log(a); // 10
+console.log(b); // 20
+
+[a, b, ...rest] = [10, 20, 30, 40, 50];
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // [30, 40, 50]
+
+({ a, b } = { a: 10, b: 20 });
+console.log(a); // 10
+console.log(b); // 20
+
+
+// Stage 4(finished) proposal
+({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // {c: 30, d: 40}
+
+ +

التفاصيل

+ +

توفر تعبيرات الكائن (Object) والمصفوفة (Array) طريقة سهلة لإنشاء حزم بيانات مخصصة.

+ +
const x = [1, 2, 3, 4, 5];
+
+ +

يَستخدِم الإسناد بالتفكيك (destructuring assignment) بنية مماثلة، ولكن على الجانب الأيسر من المهمة لتحديد القيم التي يجب فكها من مصدر المتغير الأساسي.

+ +
const x = [1, 2, 3, 4, 5];
+const [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

تشبه هذه الإمكانية الميزات الموجودة بلغات مثل Perl و Python.

+ +

+ +

تفكيك المصفوفات

+ +

تعيين المتغير الأساسي

+ +
const foo = ['one', 'two', 'three'];
+
+const [red, yellow, green] = foo;
+console.log(red); // "one"
+console.log(yellow); // "two"
+console.log(green); // "three"
+
+ +

Assignment separate from declaration

+ +

A variable can be assigned its value via destructuring separate from the variable's declaration.

+ +
let a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Default values

+ +

A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

+ +
let a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

Swapping variables

+ +

Two variables values can be swapped in one destructuring expression.

+ +

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick).

+ +
let a = 1;
+let b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+const arr = [1,2,3];
+[arr[2], arr[1]] = [arr[1], arr[2]];
+console.log(arr); // [1,3,2]
+
+
+ +

Parsing an array returned from a function

+ +

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

+ +

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

+ +
function f() {
+  return [1, 2];
+}
+
+let a, b;
+[a, b] = f();
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Ignoring some returned values

+ +

You can ignore return values that you're not interested in:

+ +
function f() {
+  return [1, 2, 3];
+}
+
+const [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+const [c] = f();
+console.log(c); // 1
+
+ +

You can also ignore all returned values:

+ +
[,,] = f();
+
+ +

Assigning the rest of an array to a variable

+ +

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

+ +
const [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+ +

Be aware that a {{jsxref("SyntaxError")}} will be thrown if a trailing comma is used on the left-hand side with a rest element:

+ +
const [a, ...b,] = [1, 2, 3];
+
+// SyntaxError: rest element may not have a trailing comma
+// Always consider using rest operator as the last element
+
+ +

Unpacking values from a regular expression match

+ +

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

+ +
function parseProtocol(url) {
+  const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+  if (!parsedURL) {
+    return false;
+  }
+  console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+  const [, protocol, fullhost, fullpath] = parsedURL;
+  return protocol;
+}
+
+console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
+
+ +

Object destructuring

+ +

Basic assignment

+ +
const user = {
+    id: 42,
+    is_verified: true
+};
+
+const {id, is_verified} = user;
+
+console.log(id); // 42
+console.log(is_verified); // true
+
+ +

Assignment without declaration

+ +

A variable can be assigned its value with destructuring separate from its declaration.

+ +
let a, b;
+
+({a, b} = {a: 1, b: 2});
+ +
+

Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

+ +

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

+ +

However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2}

+ +

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

+
+ +

Assigning to new variable names

+ +

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

+ +
const o = {p: 42, q: true};
+const {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true
+ +

Here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.

+ +

Default values

+ +

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

+ +
const {a = 10, b = 5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ +

Assigning to new variables names and providing default values

+ +

A property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is undefined.

+ +
const {a: aa = 10, b: bb = 5} = {a: 3};
+
+console.log(aa); // 3
+console.log(bb); // 5
+
+ +

Unpacking fields from objects passed as function parameter

+ +
const user = {
+  id: 42,
+  displayName: 'jdoe',
+  fullName: {
+    firstName: 'John',
+    lastName: 'Doe'
+  }
+};
+
+function userId({id}) {
+  return id;
+}
+
+function whois({displayName, fullName: {firstName: name}}) {
+  return `${displayName} is ${name}`;
+}
+
+console.log(userId(user)); // 42
+console.log(whois(user));  // "jdoe is John"
+ +

This unpacks the id, displayName and firstName from the user object and prints them.

+ +

Setting a function parameter's default value

+ +
function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
+  console.log(size, coords, radius);
+  // do some chart drawing
+}
+
+drawChart({
+  coords: {x: 18, y: 30},
+  radius: 30
+});
+ +
+

In the function signature for drawChart above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: {size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}. You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply call drawChart() without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

+
+ +

Nested object and array destructuring

+ +
const metadata = {
+  title: 'Scratchpad',
+  translations: [
+    {
+      locale: 'de',
+      localization_tags: [],
+      last_edit: '2014-04-14T08:43:37',
+      url: '/de/docs/Tools/Scratchpad',
+      title: 'JavaScript-Umgebung'
+    }
+  ],
+  url: '/en-US/docs/Tools/Scratchpad'
+};
+
+let {
+  title: englishTitle, // rename
+  translations: [
+    {
+       title: localeTitle, // rename
+    },
+  ],
+} = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

For of iteration and destructuring

+ +
const people = [
+  {
+    name: 'Mike Smith',
+    family: {
+      mother: 'Jane Smith',
+      father: 'Harry Smith',
+      sister: 'Samantha Smith'
+    },
+    age: 35
+  },
+  {
+    name: 'Tom Jones',
+    family: {
+      mother: 'Norah Jones',
+      father: 'Richard Jones',
+      brother: 'Howard Jones'
+    },
+    age: 25
+  }
+];
+
+for (const {name: n, family: {father: f}} of people) {
+  console.log('Name: ' + n + ', Father: ' + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+
+ +

Computed object property names and destructuring

+ +

Computed property names, like on object literals, can be used with destructuring.

+ +
let key = 'z';
+let {[key]: foo} = {z: 'bar'};
+
+console.log(foo); // "bar"
+
+ +

Rest in Object Destructuring

+ +

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

+ +
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
+a; // 10
+b; // 20
+rest; // { c: 30, d: 40 }
+ +

Invalid JavaScript identifier as a property name

+ +

Destructuring can be used with property names that are not valid JavaScript {{glossary("Identifier", "identifiers")}} by providing an alternative identifier that is valid.

+ +
const foo = { 'fizz-buzz': true };
+const { 'fizz-buzz': fizzBuzz } = foo;
+
+console.log(fizzBuzz); // "true"
+
+ +

Combined Array and Object Destructuring

+ +

Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

+ +
const props = [
+  { id: 1, name: 'Fizz'},
+  { id: 2, name: 'Buzz'},
+  { id: 3, name: 'FizzBuzz'}
+];
+
+const [,, { name }] = props;
+
+console.log(name); // "FizzBuzz"
+
+ +

The prototype chain is looked up when the object is deconstructed 

+ +

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

+ +
let obj = {self: '123'};
+obj.__proto__.prot = '456';
+const {self, prot} = obj;
+// self "123"
+// prot "456"(Access to the prototype chain)
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.operators.destructuring")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/index.html b/files/ar/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..a5dc098a4f --- /dev/null +++ b/files/ar/web/javascript/reference/operators/index.html @@ -0,0 +1,302 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

This chapter documents all the JavaScript language operators, expressions and keywords.

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Primary expressions

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}
+
The async function defines an async function expression.
+
{{experimental_inline}} {{jsxref("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Note: => is not an operator, but the notation for Arrow functions.

+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/new/index.html b/files/ar/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..3b39e0cf4e --- /dev/null +++ b/files/ar/web/javascript/reference/operators/new/index.html @@ -0,0 +1,178 @@ +--- +title: new operator +slug: Web/JavaScript/Reference/Operators/new +tags: + - HTTP + - OpenPractices + - البروتوكولات + - بحث + - لغة البرمجة +translation_of: Web/JavaScript/Reference/Operators/new +--- +
9 9090 jsSidebar ("عوامل التشغيل")}}
+ +

في newالمشغل يتيح للمطورين إنشاء مثيل من نوع الكائن المعرفة من قبل المستخدم أو واحد من أنواع الكائنات المضمنة التي لديه وظيفة المنشئ.

+ +
{{EmbedInteractiveExample ("pages / js / expressions-newoperator.html")}}
+ +

بناء الجملة

+ +
new constructor[([arguments])]
+ +

المعلمات

+ +
+
constructor
+
فئة أو وظيفة تحدد نوع مثيل الكائن.
+
+ +
+
arguments
+
قائمة القيم التي constructorسيتم الاتصال بها.
+
+ +

وصف

+ +

تقوم newالكلمة الرئيسية بالأشياء التالية:

+ +
    +
  1. ينشئ كائن JavaScript عاديًا فارغًا ؛
  2. +
  3. روابط (تحدد منشئ) هذا الكائن إلى كائن آخر ؛
  4. +
  5. يمر كائن تم إنشاؤه حديثا من الخطوة 1 كما في thisالسياق؛
  6. +
  7. يعود thisإذا لم الدالة بإرجاع كائن.
  8. +
+ +

يتطلب إنشاء كائن معرف من قبل المستخدم خطوتين:

+ +
    +
  1. حدد نوع الكائن عن طريق كتابة دالة.
  2. +
  3. إنشاء مثيل للكائن باستخدام new.
  4. +
+ +

لتحديد نوع كائن ، قم بإنشاء وظيفة لنوع الكائن تحدد اسمه وخصائصه. يمكن أن يكون للكائن خاصية تكون في حد ذاتها كائنًا آخر. انظر الأمثلة أدناه.

+ +

عند تنفيذ الكود ، تحدث الأشياء التالية:new Foo(...)

+ +
    +
  1. يتم إنشاء كائن جديد ، وراثة من Foo.prototype.
  2. +
  3. Fooيتم استدعاء دالة المُنشئ بالوسيطات المحددة ، وتكون thisمرتبطة بالكائن الذي تم إنشاؤه حديثًا. يكافئ ، على سبيل المثال ، إذا لم يتم تحديد قائمة وسيطة ، يتم استدعاؤه بدون وسيطات.new Foonew Foo()Foo
  4. +
  5. يصبح الكائن (ليس فارغًا ، أو خطأ ، أو 3.1415 أو أنواعًا أولية أخرى) التي تُرجعها دالة المُنشئ نتيجة newالتعبير بالكامل . إذا لم تُرجع دالة المُنشئ كائنًا بشكل صريح ، فسيتم استخدام الكائن الذي تم إنشاؤه في الخطوة 1 بدلاً من ذلك. (عادةً لا تُرجع المنشئات قيمة ، لكن يمكنهم اختيار القيام بذلك إذا كانوا يريدون تجاوز عملية إنشاء الكائن العادية.)
  6. +
+ +

يمكنك دائمًا إضافة خاصية إلى كائن محدد مسبقًا. على سبيل المثال ، car1.color = "black"تضيف العبارة خاصية colorإلى car1، وتخصص لها قيمة " black". ومع ذلك ، هذا لا يؤثر على أي كائنات أخرى. لإضافة الخاصية الجديدة إلى جميع الكائنات من نفس النوع ، يجب إضافة الخاصية إلى تعريف Carنوع الكائن.

+ +

يمكنك إضافة خاصية مشتركة إلى نوع كائن محدد مسبقًا باستخدام Function.prototypeالخاصية. يحدد هذا الخاصية التي يتم مشاركتها بواسطة جميع الكائنات التي تم إنشاؤها باستخدام هذه الوظيفة ، بدلاً من مثيل واحد فقط من نوع الكائن. تضيف التعليمة البرمجية التالية خاصية لون مع قيمة "original color"لكل كائنات النوع Car، ثم تكتب فوق تلك القيمة بالسلسلة " black" فقط في كائن المثيل car1. لمزيد من المعلومات ، انظر النموذج الأولي .

+ +
function Car() {}
+car1 = new Car();
+car2 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = 'original color';
+console.log(car1.color);    // 'original color'
+
+car1.color = 'black';
+console.log(car1.color);    // 'black'
+
+console.log(Object.getPrototypeOf(car1).color); // 'original color'
+console.log(Object.getPrototypeOf(car2).color); // 'original color'
+console.log(car1.color);   // 'black'
+console.log(car2.color);   // 'original color'
+
+ +
+

إذا لم تكتب newعامل التشغيل ، فسيتم استدعاء دالة الباني مثل أي دالة عادية ، دون إنشاء كائن. في هذه الحالة ، قيمة thisمختلفة أيضًا.

+
+ +

أمثلة

+ +

نوع الكائن ومثيل الكائن

+ +

لنفترض أنك تريد إنشاء نوع كائن للسيارات. تريد أن يتم استدعاء هذا النوع من الكائنات Car، وتريد أن يكون لها خصائص لـ make و model و year. للقيام بذلك ، يمكنك كتابة الوظيفة التالية:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

الآن يمكنك إنشاء كائن يسمى على myCarالنحو التالي:

+ +
var myCar = new Car('Eagle', 'Talon TSi', 1993);
+
+ +

تقوم هذه العبارة بإنشاء myCarوتعيين القيم المحددة لخصائصها. ثم قيمة myCar.makeالسلسلة "النسر" ، myCar.yearهو العدد الصحيح 1993 ، وهلم جرا.

+ +

يمكنك إنشاء أي عدد من carالكائنات عن طريق المكالمات إلى new. فمثلا:

+ +
var kensCar = new Car('Nissan', '300ZX', 1992);
+
+ +

خاصية الكائن التي هي نفسها كائن آخر

+ +

لنفترض أنك قمت بتعريف كائن يسمى على PersSexonالنحو التالي:

+ +
function Person(name, age, sex) {XxxXxx
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

ثم قم بإنشاء كائنين جديدين على Personالنحو التالي:

+ +
var rand = new Person('Rand McNally', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+
+ +

ثم يمكنك إعادة كتابة تعريف Carلتضمين ownerخاصية تأخذ Personكائنًا ، على النحو التالي:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

لإنشاء كائنات جديدة ، يمكنك بعد ذلك استخدام ما يلي:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+
+ +

بدلا من تمرير سلسلة حرفية أو عدد صحيح القيمة عند إنشاء كائنات جديدة، والبيانات المذكورة أعلاه تمر الكائنات randو kenكمعلمات للمالكي. لمعرفة اسم مالك الموقع car2، يمكنك الوصول إلى الخاصية التالية:

+ +
car2.owner.name
+
+ +

مواصفات

+ + + + + + + + + + + + +
تخصيص
{{SpecName ('ESDraft'، '# sec-new-worker'، 'The new Operator')}}
+ +

التوافق المتصفح

+ + + +

{{Compat ("javascript.operators.new")}}

+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/operators/object_initializer/index.html b/files/ar/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..b6df949722 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,403 @@ +--- +title: Object initializer تهيئة الكائن +slug: Web/JavaScript/Reference/Operators/Object_initializer +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +
{{JsSidebar("Operators")}}
+ +

 

+ +
+

يمكن تهيئة الكائنات باستخدام ()new Object او ()Object.create او باستخدام مهيئ الكائن (Object initializer). مهيئ الكائن هو عبارة عن قائمة من الخصائص، وكل خاصية من هذه الخصائص عبارة عن زوجين وهما، اسم الخاصية وقيمة الخاصية، يفصل بين كل زوجين بفاصلة، يمكن لهذه القائمة ان تحتوي على صفر او اكثر من هذه الازواج، محاطة بأقواس متعرجة ({}).

+ +

Syntax

+ +
var o = {};
+var o = {a: 'foo', b: 42, c: {}};
+
+var a = 'foo', b = 42, c = {};
+var o = {a: a, b: b, c: c};
+
+var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+
+ +

New notations in ECMAScript 2015

+ +

يرجى الاطلاع على جدول التوافق اسفل الصفحة. هذه التعليمات البرمجية ستؤدي إلى أخطاء syntax errors، في البيئات الغير الداعمة.

+ +
// Shorthand property names (ES2015)
+var a = 'foo', b = 42, c = {};
+var o = {a, b, c};
+
+// Shorthand method names (ES2015)
+var o = {
+  property([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+
+// Computed property names (ES2015)
+var prop = 'foo';
+var o = {
+  [prop]: 'hey',
+  ['b' + 'ar']: 'there'
+};
+ +

الوصف

+ +

مهيئ الكائن هو تعبير عن كيفية وصف وتهيئة الكائن {{jsxref("Object")}}. تتكون الكائنات من الخصائص، والتي يتم استخدامها لوصف الكائن. قيمة خاصية الكائن يمكن أن تحتوي على أنواع البيانات الأولية {{Glossary("primitive")}} كما يمكنها ايضا ان تحتوي على كائنات اخرى.

+ +

إنشاء الكائنات

+ +

يمكن إنشاء كائن فارغ بدون خصائص هكذا:

+ +
var object = {};
+ +

ميزة هذا literal او المهئ هي انه يمكنك سريعا من انشاء الكائنات وخصائصها داخل الأقواس المتعرجة. يمكنك ببساطة انشاء قائمة مكونة من زوجين key: value مفصولة بفاصلة. تقوم التعليمة البرمجية التالية بانشاء كائن مع ثلاثة خصائص والمفاتيح هي "foo", "age" و "baz". وقيم هذه المفاتيح هي string "bar", a number 42، فيما قيمة المفتاح "baz" عبارة عن كائن هو ايضا له مفتاح وقيمة.

+ +
var object = {
+  foo: 'bar',
+  age: 42,
+  baz: {myProp: 12}
+}
+ +

الوصول إلى الخصائص

+ +

حالما تقوم بإنشاء كائن، سترغب في قراءة الخصائص أو تغييرها. يمكن الوصول إلى خصائص الكائن باستخدام نقطة التدوين او عن طريق الاقواس المربعة. راجع property accessors لمزيد من المعلومات.

+ +
object.foo; // "bar"
+object['age']; // 42
+
+object.foo = 'baz';
+
+ +

تعريف الخصائص

+ +

تعلمنا للتو كيفية التعبير عن الخصائص باستخدام المهيئ. تجدر الإشارة الى انه في كثير من الأحيان، سترغب في تمرير متغيرات الى الكائن. يمكنك تمريها على هذا النحو:

+ +
var a = 'foo',
+    b = 42,
+    c = {};
+
+var o = {
+  a: a,
+  b: b,
+  c: c
+};
+ +

ECMAScript 2015، جاءت بطريقة مختصرة لتحقيق نفس الغرض:

+ +
var a = 'foo',
+    b = 42,
+    c = {};
+
+// Shorthand property names (ES2015)
+var o = {a, b, c};
+
+// In other words,
+console.log((o.a === {a}.a)); // true
+
+ +

أسماء الخصائص المكررة

+ +

عند استخدام الخصائص باسماء مكررة، سوف تقوم الخاصية الثانية بالكتابة فوق  الأولى.

+ +
var a = {x: 1, x: 2};
+console.log(a); // {x: 2}
+
+ +

في ECMAScript 5 strict mode تكرار اسماء الخصائص سينتج عنها اخطاء {{jsxref("SyntaxError")}}.

+ +
function haveES2015DuplicatePropertySemantics() {
+  'use strict';
+  try {
+    ({prop: 1, prop: 2});
+
+    // No error thrown, duplicate property names allowed in strict mode
+    return true;
+  } catch(e) {
+    // Error thrown, duplicates prohibited in strict mode
+    return false;
+  }
+}
+ +

تعريف الوظائف

+ +

خاصية الكائن يمكن أن تشير أيضا إلى الوظائف function او getter او setter.

+ +
var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+ +

في ECMAScript 2015، اصبح الاختصار متاحا، حيث أن الكلمة المحجوزة function لم تعد ضرورية.

+ +
// Shorthand method names (ES2015)
+var o = {
+  property([parameters]) {},
+  get property() {},
+  set property(value) {},
+  * generator() {}
+};
+
+ +

في ECMAScript 2015، هناك طريقة لاختصار تعريف الخصائص التي قيمها generator functions :

+ +
var o = {
+  * generator() {
+    ...........
+  }
+};
+ +

في ECMAScript 5، سوف تكتب هكذا (لكن لاحظ أن ES5 قد لا توجد مولدات):

+ +
var o = {
+  generator: function *() {
+    ...........
+  }
+};
+ +

لمزيد من المعلومات والأمثلة حول الوظائف، راجع method definitions.

+ +

أسماء الخصائص المحوسبة

+ +

ابتداءا من ECMAScript 2015، مهئ الكائن اصبح يدعم اسماء الخصائص المحوسبة. والتي تسمح لك بوضع التعبير بين أقواس مربعة []، والتي ستعتمد كاسم للخاصية. وهي متسقة مع الاقواس المربعة التي تستخدم للوصول الى الخصائص، property accessor والتي قد تستخدم بالفعل لقراءة وتعيين الخصائص. الآن يمكنك استخدام نفس التعبير المستخدم في object literals، هكذا:

+ +
// Computed property names (ES2015)
+var i = 0;
+var a = {
+  ['foo' + ++i]: i,
+  ['foo' + ++i]: i,
+  ['foo' + ++i]: i
+};
+
+console.log(a.foo1); // 1
+console.log(a.foo2); // 2
+console.log(a.foo3); // 3
+
+var param = 'size';
+var config = {
+  [param]: 12,
+  ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
+};
+
+console.log(config); // {size: 12, mobileSize: 4}
+ +

Prototype mutation

+ +

الخاصية المعرفة على هذا الشكل  proto__: value__ او proto__": value__" لا تقوم بإنشاء خاصية جديدة باسم  __proto__. بل تقوم  بتغيير [[Prototype]] الكائن نفسه، وذالك من خلال اسناد قيمة له تكون عبارة عن كائن اخر او null. (إذا كانت القيمة المسندة ليست كائن أو null، فلا يتم تغيير شئ في الكائن) على سبيل المثال:

+ +
var obj1 = {x: 10};
+
+var obj2 = {
+	y: 20,
+    __proto__: obj1
+};
+console.log( obj2.x ); // log: 10 
+ +

تبين التعليمة البرمجية التالية، بعض التحققات من بعض انواع التغييرات:

+ +
var obj1 = {};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);  // true
+
+var obj2 = {__proto__: null};
+assert(Object.getPrototypeOf(obj2) === null);              // true
+
+var protoObj = {};
+var obj3 = {'__proto__': protoObj};
+assert(Object.getPrototypeOf(obj3) === protoObj);          // true
+
+var obj4 = {__proto__: 'not an object or null'};
+assert(Object.getPrototypeOf(obj4) === Object.prototype);  // true
+assert(!obj4.hasOwnProperty('__proto__'));                 // true
+
+ +

لا يسمح بتغيير ال prototype الا مرة واحدة في object literal، واكثر من تغيير في ال prototype سيؤدي الى syntax error.

+ +

الخواص التي لا تستخدم النقطتين (:) تصبح خواص عادية وتتصرف كاي اسم اخر، وليس لها علاقة بتغيير ال prototype:

+ +
var __proto__ = 'variable';
+
+var obj1 = {__proto__};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+assert(obj1.hasOwnProperty('__proto__'));
+assert(obj1.__proto__ === 'variable');
+
+var obj2 = {__proto__() { return 'hello'; }};
+assert(obj2.__proto__() === 'hello');
+
+var obj3 = {['__prot' + 'o__']: 17};
+assert(obj3.__proto__ === 17);
+
+ +

Object literal notation vs JSON

+ +

ال object literal notation ليس هو نفسه JavaScript Object Notation (JSON). على الرغم من أنها تبدو مشابهة، الا ان هنالك اختلافات كبيرة بينهما:

+ + +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}initial definition.
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}getter and setter added.
{{SpecName('ES2015', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ES2015')}}Shorthand method/property names and computed property names added.
{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}111
Computed property names{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}347.1
Shorthand property names{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("33")}}{{CompatNo}}349
Shorthand method names{{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}349
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}111{{CompatChrome(1.0)}}
Computed property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}347.1{{CompatNo}}
Shorthand property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("33")}}{{CompatNo}}349{{CompatNo}}
Shorthand method names{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile("34")}}{{CompatNo}}349{{CompatChrome(42.0)}}
+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/operator_precedence/index.html b/files/ar/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..8b71a69143 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,420 @@ +--- +title: أسبقية العوامل +slug: Web/JavaScript/Reference/Operators/Operator_Precedence +tags: + - أسبقية العوامل + - جافا سكربت + - عوامل رياضية +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

أسبقية العوامل تحدد الطريقة التي يتم بها تعامل كل من العوامل مع بعضها. العوامل ذات الأسبقية العليا تسبق العوامل ذات الأسبقية المنخفضة.

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

الترابطات 

+ +

تحدد الترابطات الطريقة التي يتم بها تحليل العوامل التي لها نفس الأسبقية. على سبيل المثال، لنقل أن:

+ +
a OP b OP c
+
+ +

تعني كلمة رابط - يسار (من اليسار إلى اليمين) أنها تتم معالجتها كـ a OP b) OP c) ، بينما تعني رابط - يمين (من اليمين إلى اليسار) أنها تُفسَّر على أنها (a OP (b OP c. عوامل التعيين هي رابط-يمين، حيث يمكنك كتابة:

+ +
a = b = 5;
+
+ +

مع النتيجة المتوقعة أن تحصل a و b على القيمة 5. وذلك لأن عامل التعيين يُرجع القيمة التي تم تعيينها. أولاً، يتم تعيين b على 5. ثم يتم تعيين a أيضًا على 5 ، قيمة الإرجاع b = 5 ، ويعرف أيضًا باسم المعامل الأيمن للتعيين.

+ +

أمثلة:

+ +
3 > 2 && 2 > 1
+// returns true تعيد لنا صح
+
+3 > 2 > 1
+// returns false because 3 > 2 is true, and true > 1 is false تعيد خطأ لأن 3>2 هي صحيحة، وصح > 1 هو خطأ
+// Adding parentheses makes things clear: (3 > 2) > 1 إضافة الأقواس تجعل كل شيء واضح: (3>2) 1
+ +

الجدول

+ +

الجدول التالي مرتب من (20) الأعلى أسبقية إلى الأقل وهو (1).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrecedenceOperator typeAssociativityIndividual operators
21{{jsxref("Operators/Grouping", "Grouping", "", 1)}} تجميعn/a( … )
20{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}} الوصول الى عنصر +

left-to-right

+ +

من اليسار الى اليمين

+
… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}} الوصول لعنصر محسوب +

left-to-right

+ +

من اليسار الى اليمين

+
… [ … ]
{{jsxref("Operators/new","new")}} (with argument list) جديد مع (قائمة معاملات)n/anew … ( … )
Function Call استدعاء دالة +

left-to-right

+ +

من اليسار الى اليمين

+
… ( )
Optional chaining تسلسل اختياري +

left-to-right

+ +

من اليسار الى اليمين

+
?.
19{{jsxref("Operators/new","new")}} (without argument list) جديد .. بدون قائمة معاملات +

right-to-left

+ +

من اليمين الى اليسار

+
new …
18{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}} إضافة بعد إعادة النتيجة n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}} طرح بعد إعادة النتيجة… --
17Logical NOT نفي منطقي +

right-to-left

+ +

من اليمين الى اليسار

+
! …
Bitwise NOT نفي بالبت~ …
Unary Plus + أحادي+ …
Unary Negation - أحادي- …
Prefix Increment إضافة قبل إعادة النتيجة++ …
Prefix Decrement طرح قبل إعادة النتيجة-- …
{{jsxref("Operators/typeof", "typeof")}} نوع الtypeof …
{{jsxref("Operators/void", "void")}} مجموعة خاليةvoid …
{{jsxref("Operators/delete", "delete")}} حذفdelete …
{{jsxref("Operators/await", "await")}} انتظارawait …
16Exponentiation أُس (الرفع الى قوة) +

right-to-left

+ +

من اليمين الى اليسار

+
… ** …
15Multiplication الضرب +

left-to-right

+ +

من اليسار الى اليمين

+
… * …
Division القسمة… / …
Remainder الباقي… % …
14Addition الجمع +

left-to-right

+ +

من اليسار الى اليمين

+
… + …
Subtraction الطرح… - …
13Bitwise Left Shift إزاحة لليسار بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… << …
Bitwise Right Shift إزاحة لليمين بالبت… >> …
Bitwise Unsigned Right Shift… >>> …
12Less Than أصغر من +

left-to-right

+ +

من اليسار الى اليمين

+
… < …
Less Than Or Equal أصغر من أو يساوي… <= …
Greater Than أكبر من… > …
Greater Than Or Equal أكبر من أو يساوي… >= …
{{jsxref("Operators/in", "in")}} في… in …
{{jsxref("Operators/instanceof", "instanceof")}} مشتق من … instanceof …
11Equality يساوي +

left-to-right

+ +

من اليسار الى اليمين

+
… == …
Inequality لا يساوي… != …
Strict Equality مساواة قطعية… === …
Strict Inequality لا يساوي قطعيا… !== …
10Bitwise AND و بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… & …
9Bitwise XOR  +

left-to-right

+ +

من اليسار الى اليمين

+
… ^ …
8Bitwise OR أو بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… | …
7Nullish coalescing operator +

left-to-right

+ +

من اليسار الى اليمين

+
… ?? …
6Logical AND و المنطقية +

left-to-right

+ +

من اليسار الى اليمين

+
… && …
5Logical OR أو المنطقية +

left-to-right

+ +

من اليسار الى اليمين

+
… || …
4Conditional الشرطية +

right-to-left

+ +

من اليمين الى اليسار

+
… ? … : …
3Assignment التعيين +

right-to-left

+ +

من اليمين الى اليسار

+
… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}} +

right-to-left

+ +

من اليمين الى اليسار

+
yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Comma / Sequence فاصلة / تسلسل +

left-to-right

+ +

من اليسار الى اليمين

+
… , …
diff --git a/files/ar/web/javascript/reference/operators/this/index.html b/files/ar/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..4e86b7e937 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/this/index.html @@ -0,0 +1,381 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar ("عوامل التشغيل")}}
+ +

A الدالة thisالكلمة تتصرف بشكل مختلف قليلا في جافا سكريبت بالمقارنة مع اللغات الأخرى. كما أن لديها بعض الاختلافات بين الوضع الصارم والوضع غير الصارم.

+ +

في معظم الحالات ، thisيتم تحديد القيمة من خلال كيفية استدعاء دالة (ربط وقت التشغيل). لا يمكن تعيينه عن طريق التعيين أثناء التنفيذ ، وقد يكون مختلفًا في كل مرة يتم استدعاء الوظيفة. قدم ES5 طريقة {{jsxref ("Function.prototype.bind ()"، "bind ()")}} إلى {{jsxref ('Operators / this'، ") تعيين قيمة الوظيفة thisبغض النظر عن كيفية تسميتها" قدم كل من "The_bind_method" و 1)}} و ES2015 دالات الأسهم التي لا توفر ربطًا خاصًا بها this(فهي تحتفظ thisبقيمة السياق المعجم المرفق).

+ +
{{EmbedInteractiveExample ("pages / js / expressions-this.html")}}
+ + + +

بناء الجملة

+ +
هذه
+ +

القيمة

+ +

خاصية سياق التنفيذ (عام ، أو وظيفة ، أو تقييم) التي ، في الوضع غير الصارم ، تكون دائمًا مرجعًا إلى كائن وفي الوضع الصارم يمكن أن تكون أي قيمة.

+ +

السياق العالمي

+ +

في سياق التنفيذ العام (خارج أي وظيفة) ، thisيشير إلى الكائن العام سواء في الوضع الصارم أم لا.

+ +
// في متصفحات الويب ، يكون كائن النافذة أيضًا هو الكائن العام:
+console.log (هذه النافذة ===) ؛ // صحيح
+
+أ = 37 ؛
+console.log (window.a) ؛ // 37
+
+this.b = "MDN" ؛
+console.log (window.b) // "MDN"
+console.log (ب) // "MDN"
+
+ +
+

ملاحظة: يمكنك دائمًا الحصول بسهولة على الكائن العام باستخدام خاصية {{jsxref ("globalThis")}} العمومية ، بغض النظر عن السياق الحالي الذي تعمل فيه التعليمات البرمجية الخاصة بك.

+
+ +

سياق الوظيفة

+ +

داخل الدالة ، thisتعتمد القيمة على كيفية استدعاء الوظيفة.

+ +

مكالمة بسيطة

+ +

نظرًا لأن الشفرة التالية ليست في وضع صارم ، ولأن القيمة thisلم يتم تعيينها بواسطة المكالمة ، thisفسيتم تعيينها افتراضيًا على الكائن العام ، وهو {{domxref ("Window"، "window")}} في المتصفح.

+ +
الدالة f1 () {
+  أعد هذا ؛
+}}
+
+// في متصفح:
+f1 () === نافذة ؛ // صحيح
+
+// في العقدة:
+f1 () === عام ؛ // صحيح
+ +

ومع ذلك ، في الوضع الصارم ، إذا thisلم يتم تعيين القيمة عند إدخال سياق التنفيذ ، فإنها تظل كما undefinedهو موضح في المثال التالي:

+ +
الدالة f2 () {
+  "استخدام صارم" ؛ // انظر الوضع الصارم
+  أعد هذا ؛
+}}
+
+f2 () === غير معرّف ؛ // صحيح
+
+ +
في المثال الثاني ، thisيجب أن يكون {{jsxref ("undefined")}} ، لأنه f2تم استدعاؤه مباشرةً وليس كطريقة أو خاصية لكائن (مثل window.f2()). لم يتم تنفيذ هذه الميزة في بعض المتصفحات عندما بدأوا في دعم الوضع الصارم لأول مرة . ونتيجة لذلك ، أعادوا windowالكائن بشكل غير صحيح .
+ +

لتعيين قيمة thisإلى قيمة معينة عند استدعاء دالة ، استخدم {{jsxref ("Function.prototype.call ()" أو "call ()")}} أو {{jsxref ("Function.prototype.apply ( ) "،" Apply () ")}} كما في الأمثلة التالية.

+ +

مثال 1

+ +
// يمكن تمرير كائن باعتباره الوسيطة الأولى للاتصال أو التطبيق وهذا سوف يرتبط به.
+var obj = {a: 'Custom'} ؛
+
+// تم تعيين هذه الخاصية على الكائن العام
+var a = 'Global'؛
+
+الدالة whatsThis () {
+  أعد هذا. // تعتمد قيمة هذا على كيفية استدعاء الوظيفة
+}}
+
+ما هذا()؛ // "عالمي"
+whatsThis.call (obj) ؛ // 'مخصص'
+whatsThis.apply (obj) ؛ // 'مخصص'
+
+ +

مثال 2

+ +
إضافة دالة (ج ، د) {
+  إرجاع هذا. a + this.b + c + d ؛
+}}
+
+var o = {a: 1، b: 3} ؛
+
+// المعلمة الأولى هي الكائن المطلوب استخدامه كـ
+// 'this' ، يتم تمرير المعلمات اللاحقة كـ 
+// الوسيطات في استدعاء الوظيفة
+add.call (س ، 5 ، 7) ؛ // 16
+
+// المعلمة الأولى هي الكائن المطلوب استخدامه كـ
+// 'this' ، والثاني عبارة عن مصفوفة
+يتم استخدام // members كوسيطة في استدعاء دالة
+add.apply (س ، [10 ، 20]) ؛ // 34
+
+ +

علما بأن في الوضع غير صارمة، مع callو apply، إذا كانت القيمة التي تم تمريرها كما thisليست كائن، سيتم إجراء محاولة لتحويله إلى كائن باستخدام الداخلية ToObjectالعملية. لذا ، إذا كانت القيمة التي تم تمريرها بدائية مثل 7أو 'foo'، سيتم تحويلها إلى كائن باستخدام المُنشئ ذي الصلة ، لذلك 7يتم تحويل الرقم البدائي إلى كائن كما لو كان بواسطة new Number(7)والسلسلة 'foo'إلى كائن كما لو كان new String('foo')، على سبيل المثال

+ +
شريط الوظائف () {
+  console.log (Object.prototype.toString.call (this)) ؛
+}}
+
+bar.call (7) ؛ // [رقم الكائن]
+bar.call ('foo') ؛ // [سلسلة الكائن]
+
+ +

على bindطريقة

+ +

قدم ECMAScript 5 {{jsxref ("Function.prototype.bind ()")}}}. f.bind(someObject)يؤدي الاستدعاء إلى إنشاء وظيفة جديدة بنفس الجسم والنطاق f، ولكن thisفي حالة حدوثها في الوظيفة الأصلية ، في الوظيفة الجديدة ، يتم ربطها بشكل دائم بالحجة الأولى bind، بغض النظر عن كيفية استخدام الوظيفة.

+ +
دالة f () {
+  أعد هذا.
+}}
+
+var g = f.bind ({a: 'azerty'}) ؛
+console.log (g ()) ؛ // azerty
+
+var h = g.bind ({a: 'yoo'}) ؛ // bind يعمل مرة واحدة فقط!
+console.log (h ()) ؛ // azerty
+
+var o = {a: 37، f: f، g: g، h: h} ؛
+console.log (oa، of ()، og ()، oh ())؛ // 37،37، azerty، azerty
+
+ +

وظائف السهم

+ +

في دوال السهم ، thisيحتفظ بقيمة السياق المعجم المتضمن this. في الكود العام ، سيتم تعيينه على الكائن العام:

+ +
var globalObject = هذا ؛
+var foo = (() => this) ؛
+console.log (foo () === globalObject) ؛ // صحيح
+ +
+

ملاحظة: إذا thisتم تمرير الوسيطة إلى call، bindأو applyعند استدعاء وظيفة السهم ، فسيتم تجاهلها. لا يزال بإمكانك إضافة وسيطات إلى المكالمة ، ولكن thisArgيجب ضبط الوسيطة الأولى ( ) على null.

+
+ +
// Call كطريقة لكائن
+var obj = {func: foo} ؛
+console.log (obj.func () === globalObject) ؛ // صحيح
+
+// محاولة تعيين هذا باستخدام المكالمة
+console.log (foo.call (obj) === globalObject) ؛ // صحيح
+
+// جرت محاولة ضبط ذلك باستخدام الربط
+foo = foo.bind (obj) ؛
+console.log (foo () === globalObject) ؛ // صحيح
+ +

مهما كانت، fooالصورة thisيتم تعيين إلى ما كانت عليه عندما تم إنشاؤه (في المثال أعلاه، الكائن العالمي). وينطبق الشيء نفسه على دالات الأسهم التي تم إنشاؤها داخل دوال أخرى: thisبقايا تلك السياق المعجمية المرفقة.

+ +
// إنشاء كائن بشريط أسلوب يقوم بإرجاع دالة
+// يعيد هذا. يتم إنشاء الدالة التي تم إرجاعها كـ
+// دالة سهم ، لذا فهي مرتبطة بشكل دائم بـ
+// هذه الدالة المرفقة. يمكن تعيين قيمة الشريط
+// في المكالمة ، والتي تحدد بدورها قيمة 
+// عادت الدالة.
+var obj = {
+  شريط: الوظيفة () {
+    var x = (() => this) ؛
+    العودة س ؛
+  }}
+} ؛
+
+// Call bar كطريقة للهدف ، وضبط هذا الأمر على obj
+// تعيين مرجع للدالة التي تم إرجاعها إلى fn
+var fn = obj.bar () ،
+
+// Call fn دون تعيين هذا ، سيكون الوضع الافتراضي عادةً
+// إلى الكائن العام أو غير محدد في الوضع الصارم
+console.log (fn () === obj) ؛ // صحيح
+
+// لكن احذر إذا رجعت إلى طريقة الكائن بدون تسميتها
+var fn2 = obj.bar ،
+// استدعاء وظيفة السهم هذا من داخل طريقة الشريط ()
+// سيعود الآن النافذة ، لأنه يتبع هذا من fn2.
+console.log (fn2 () () == window) ؛ // صحيح
+
+ +

في أعلاه ، تم تعيين الوظيفة (يطلق عليها الوظيفة المجهولة أ) obj.barلإرجاع وظيفة أخرى (يطلق عليها الوظيفة المجهولة ب) التي تم إنشاؤها كدالة سهم. ونتيجة لذلك، وظيفة B في thisتعيين دائم لل thisمن obj.bar(وظيفة A) عندما دعا. عندما يتم استدعاء الدالة التي تم إرجاعها (الوظيفة B) ، thisستكون دائمًا ما تم تعيينها عليه في البداية. في المثال رمز أعلاه، وظيفة باء thisمن المقرر أن وظيفة A و thisالذي هو obj، لذلك لا يزال المقرر أن objحتى عندما دعا بطريقة من شأنها أن تحدد عادة في thisل undefinedأو الكائن العالمي (أو أي طريقة أخرى كما في المثال السابق في عالمي سياق التنفيذ).

+ +

كطريقة كائن

+ +

عندما يتم استدعاء دالة كطريقة لكائن ما ، thisيتم تعيينها على الكائن الذي يتم استدعاء الطريقة.

+ +

في المثال التالي ، عندما o.f()يتم استدعاء ، داخل الوظيفة thisمنضمة إلى oالكائن.

+ +
var o = {
+  الدعامة: 37 ،
+  و: الوظيفة () {
+    أعد هذا. prop؛
+  }}
+} ؛
+
+console.log (من ()) ؛ // 37
+
+ +

لاحظ أن هذا السلوك لا يتأثر على الإطلاق بكيفية أو مكان تعريف الوظيفة. في المثال السابق ، قمنا بتعريف الوظيفة المضمنة fكعضو أثناء تعريف o. ومع ذلك ، كان بإمكاننا تحديد الوظيفة بسهولة ثم إرفاقها بها لاحقًا o.f. يؤدي القيام بذلك إلى نفس السلوك:

+ +
var o = {prop: 37} ؛
+
+وظيفة مستقلة () {
+  أعد هذا. prop؛
+}}
+
+of = مستقل ؛
+
+console.log (من ()) ؛ // 37
+
+ +

يوضح هذا أنه من المهم فقط أن يتم استدعاء الوظيفة من fعضو o.

+ +

وبالمثل ، thisلا يتأثر الربط إلا بمرجع العضو المباشر. في المثال التالي ، عندما نستدعي الوظيفة ، نسميها كطريقة gللكائن o.b. هذه المرة أثناء التنفيذ ، thisسيتم الرجوع إلى داخل الوظيفة o.b. حقيقة أن الكائن هو نفسه عضو oليس له أي عواقب ؛ المرجع الأكثر فورية هو كل ما يهم.

+ +
ob = {g: Independent، prop: 42} ؛
+console.log (obg ()) ؛ // 42
+
+ +

this في سلسلة النموذج الأولي للكائن

+ +

ينطبق نفس المفهوم على الأساليب المحددة في مكان ما على سلسلة النموذج الأولي للكائن. إذا كانت الطريقة موجودة في سلسلة نموذجية للكائن ، thisفيشير إلى الكائن الذي تم استدعاء الطريقة ، كما لو كانت الطريقة موجودة على الكائن.

+ +
var o = {f: function () {return this.a + this.b؛ }} ؛
+var p = Object.create (o) ؛
+السلطة الفلسطينية = 1 ؛
+pb = 4 ؛
+
+console.log (pf ()) ؛ // 5
+
+ +

في هذا المثال ، الكائن الذي تم تعيينه للمتغير pليس له fخاصية خاصة به ، بل يرثه من النموذج الأولي الخاص به. ولكن لا يهم أن fيجد البحث في النهاية عضوًا يحمل هذا الاسم o؛ بدأ البحث كمرجع إلى p.f، لذا thisداخل الوظيفة تأخذ قيمة الكائن المشار إليه باسم p. هذا ، حيث fيطلق عليه أسلوبًا p، thisيشير إليه p. هذه ميزة مثيرة للاهتمام في وراثة النموذج الأولي لجافا سكريبت.

+ +

this مع مُدرب أو مُدرب

+ +

مرة أخرى ، نفس الفكرة صحيحة عندما يتم استدعاء دالة من getter أو setter. this ترتبط الوظيفة المستخدمة كجلب أو أداة ضبط بالكائن الذي يتم تعيين الخاصية أو الحصول عليها منه.

+ +
الدالة () {
+  إرجاع this.a + this.b + this.c ؛
+}}
+
+var o = {
+  أ: 1 ،
+  ب: 2 ،
+  ج: 3 ،
+  الحصول على المتوسط ​​() {
+    العودة (this.a + this.b + this.c) / 3 ؛
+  }}
+} ؛
+
+Object.defineProperty (o، 'sum'، {
+    get: sum، enumerable: true، configurable: true})؛
+
+console.log (o. avage، o.sum) ؛ // 2 ، 6
+
+ +

كمنشئ

+ +

عند استخدام دالة كمنشئ (باستخدام الكلمة الرئيسية {{jsxref ("Operators / new"، "new")}}) ، thisفإنها مرتبطة بالعنصر الجديد الذي يتم إنشاؤه.

+ +
+

على الرغم من أن الإعداد الافتراضي للمنشئ هو إرجاع الكائن المشار إليه this، فإنه يمكنه بدلاً من ذلك إرجاع كائن آخر (إذا لم تكن القيمة المرجعة كائنًا ، فسيتم thisإرجاع الكائن).

+
+ +
/ *
+ * يعمل المنشئ على النحو التالي:
+ *
+ * وظيفة MyConstructor () {
+ * // كود الجسم للوظيفة الفعلية يظهر هنا.  
+ * // إنشاء خصائص على | هذا | مثل
+ * // مرغوب من خلال التنازل عنها. على سبيل المثال ،
+ * this.fum = "nom" ؛
+ * // إلى آخره...
+ *
+ * // إذا كانت الوظيفة تحتوي على بيان إرجاع ذلك
+ * // يقوم بإرجاع كائن ، سيكون هذا الكائن هو
+ * // نتيجة | جديد | التعبير. غير ذلك،
+ * // نتيجة التعبير هي الكائن
+ * // مرتبط حاليًا بـ | this |
+ * // (أي الحالة الشائعة التي تُرى عادةً).
+ *}
+ * /
+
+الدالة C () {
+  this.a = 37 ؛
+}}
+
+var o = new C () ،
+Console.log (oa) ؛ // 37
+
+
+الدالة C2 () {
+  this.a = 37 ؛
+  العودة {أ: 38} ؛
+}}
+
+o = C2 () جديد ؛
+Console.log (oa) ؛ // 38
+
+ +

في المثال الأخير ( C2) ، لأنه تم إرجاع كائن أثناء البناء ، thisيتم التخلص من الكائن الجديد الذي كان مرتبطًا به ببساطة. (هذا يجعل العبارة " this.a = 37;" رمزًا ميتًا بشكل أساسي . ليس ميتًا تمامًا لأنه يتم تنفيذه ، ولكن يمكن إزالته بدون أي تأثيرات خارجية.)

+ +

كمعالج حدث DOM

+ +

عند استخدام دالة كمعالج للأحداث ، thisيتم تعيينها على العنصر الذي يتم وضع المستمع عليه (بعض المتصفحات لا تتبع هذا الاصطلاح للمستمعين المضافين ديناميكيًا بأساليب أخرى غير {{domxref ("EventTarget / addEventListener"، "addEventListener" () ")}}).

+ +
// عند الاتصال كمستمع ، يحول العنصر ذي الصلة إلى اللون الأزرق
+دالة bluify (e) {
+  // دائما صحيح او صادق
+  console.log (هذا === e.currentTarget) ؛
+  // true عندما يكون currentTarget والهدف هما نفس الكائن
+  console.log (هذا === e.target) ؛
+  this.style.backgroundColor = '# A5D9F3' ؛
+}}
+
+// احصل على قائمة بكل عنصر في المستند
+var Elements = document.getElementsByTagName ('*') ؛
+
+// أضف bluify كمستمع فوق حتى عندما
+تم النقر على عنصر // ، ويتحول إلى اللون الأزرق
+for (var i = 0؛ i <element.length؛ i ++) {
+  العناصر [i] .addEventListener ('click'، bluify، false) ؛
+}}
+ +

في معالج حدث مضمن

+ +

عندما يتم استدعاء الرمز من معالج مضمّن في الحدث ، thisيتم تعيينه على عنصر DOM الذي يتم وضع المستمع عليه:

+ +
<button onclick = "alert (this.tagName.toLowerCase ())؛">
+  تظهر هذه
+</button>
+
+ +

يظهر التنبيه أعلاه button. لاحظ أن الكود الخارجي فقط هو الذي تم thisضبطه بهذه الطريقة:

+ +
<button onclick = "alert ((function () {return this؛}) ())؛">
+  أظهر هذا الداخلية
+</button>
+
+ +

في هذه الحالة ، thisلم يتم تعيين الوظيفة الداخلية ، لذا فإنها تُرجع الكائن العام / النافذة (أي الكائن الافتراضي في الوضع غير الصارم حيث thisلا يتم تعيينه بواسطة المكالمة).

+ +

مواصفات

+ + + + + + + + + + + + +
تخصيص
{{SpecName ('ESDraft'، '# sec-this-keyword'، 'The this keyword')}}
+ +

التوافق المتصفح

+ + + +

{{Compat ("javascript.operators.this")}}

+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/statements/index.html b/files/ar/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..b9fd7f94a0 --- /dev/null +++ b/files/ar/web/javascript/reference/statements/index.html @@ -0,0 +1,141 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarations

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/statements/return/index.html b/files/ar/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..191ab5296c --- /dev/null +++ b/files/ar/web/javascript/reference/statements/return/index.html @@ -0,0 +1,145 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

ال return ينهي البيان تنفيذ الوظيفة ويحدد قيمة ليتم ارجاعها الى دالة الاستدعاء

+ +
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
+ + + +

بناء الجملة

+ +
return [expression]; 
+ +
+
expression
+
التعبير المراد استرجاع قيمتة. اذا تم حذفه, فسيتم ارجاع undefined بدلاً من ذالك
+
+ +

الوصف

+ +

عند استخدام عبارة return في جسم الدالة,يتم ايقاف تنفيذ الوظيفة.اذا تم تحديد ذالك,يتم ارجاع قيمة معينة الى دالة الاستدعاء.على سبيل المثال,تعرض الدالة التالية مربع سعتها , x,حيث x هي رقم.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

اذا تم حذف القيمة,يتم ارجاع undefined بدلاُ من ذالك

+ +

تعطل عبارات الارجاع التالية تنفيذ الوظيفة

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

الادراج التلقائي للفاصلة المنقوطة (Semicolon)

+ +

تتاثر عبارة الارجاع بادراج الفاصلة المنقوطة تلقائياُُ (ASI) .

+ +

لا يُسمح بفاصل سطر بين الكلمة الاساسية return  و التعبير

+ +
return
+a + b;
+
+ +

is transformed by ASI into:

+ +
return;
+a + b;
+
+ +

The console will warn "unreachable code after return statement".

+ +
Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a return statement.
+ +

To avoid this problem (to prevent ASI), you could use parentheses:

+ +
return (
+  a + b
+);
+
+ +

Examples

+ +

Interrupt a function

+ +

A function immediately stops at the point where return is called.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

Returning a function

+ +

See also the article about Closures.

+ +
function magic() {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.return")}}

+ +

See also

+ + + +
+
+
diff --git "a/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" new file mode 100644 index 0000000000..d3789ba7bd --- /dev/null +++ "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" @@ -0,0 +1,165 @@ +--- +title: getter +slug: Web/JavaScript/Reference/الدوال/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +

The get صينطاكس طعمنيققbinds an object property to a function that will be called when that property is looked up.

+ +
{{EmbedInteractiveExample("pages/js/functions-getter.html")}}
+ + + +

Syntax

+ +
{get prop() { ... } }
+{get [expression]() { ... } }
+ +

Parameters

+ +
+
prop
+
rty to bind to the given fun-tion.
+
expression
+
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.
+
+ +

Description

+ +

احا الشبشب ضاع احا دا كان ةبصباع

+ +

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

+ +

Note the following when working with the get syntax:

+ + + +

Examples

+ +

Defining a getter on new objects in object initializers

+ +

This will create a pseudo-property latest for object obj, which will return the last array item in log.

+ +
const obj = {
+  log: ['example','test'],
+  get latest() {
+    if (this.log.length === 0) return undefined;
+    return this.log[this.log.length - 1];
+  }
+}
+console.log(obj.latest); // "test"
+
+ +

Note that attempting to assign a value to latest will not change it.

+ +

Deleting a getter using the delete operator

+ +

If you want to remove the getter, you can just {{jsxref("Operators/delete", "delete")}} it:

+ +
delete obj.latest;
+
+ +

Defining a getter on existing objects using defineProperty

+ +

To append a getter to an existing object later at any time, use {{jsxref("Object.defineProperty()")}}.

+ +
const o = {a: 0};
+
+Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } });
+
+console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
+ +

Using a computed property name

+ +
const expr = 'foo';
+
+const obj = {
+  get [expr]() { return 'bar'; }
+};
+
+console.log(obj.foo); // "bar"
+ +

Smart / self-overwriting / lazy getters

+ +

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.

+ +

An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or "memoized") getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:

+ + + +
+

This means that you shouldn’t write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.

+ +

Note that getters are not “lazy” or “memozied” by nature; you must implement this technique if you desire this behavior.

+
+ +

In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value getsreturn this.notifier = document.getElementById('bookmarked-notification-anchor'); },

+ +

For Firefox code, see also the XPCOMUtils.jsm code module, which defines the defineLazyGetter() function.

+ +

get vs. defineProperty

+ +

While using the get keyword and {{jsxref("Object.defineProperty()")}} have similar results, there is a subtle difference between the two when used on {{jsxref("classes")}}.

+ +

When using get the property will be defined on the instance's prototype, while using {{jsxref("Object.defineProperty()")}} the property will be defined on the instance it is applied to.

+ +
class Example {
+  get hello() {
+    return 'world';
+  }
+}
+
+const obj = new Example();
+console.log(obj.hello);
+// "world"
+
+console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
+// undefined
+
+console.log(
+  Object.getOwnPropertyDescriptor(
+    Object.getPrototypeOf(obj), 'hello'
+  )
+);
+// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions.get")}}

+ +

See also

+ + diff --git "a/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" new file mode 100644 index 0000000000..368d8af03d --- /dev/null +++ "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" @@ -0,0 +1,645 @@ +--- +title: الدوال +slug: Web/JavaScript/Reference/الدوال +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

Functions are not the same as procedures. A function always returns a value, whereas a procedure might not.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Declare variable 'mycar';
+  * create and initialize a new Object;
+  * assign reference to it to 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Pass object reference to the function */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' as the value of the 'brand' property
+  * of the object, as changed to by the function.
+  */
+ console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details):

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function declaration (function* statement)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +
+

Note: Default and rest parameters are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +
+

Note: Method definitions are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Function constructor vs. function declaration vs. function expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x == 0) {            // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y == 10) {     // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015 (ES6), functions inside blocks are now scoped to that block. Prior to ES6, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (0) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' == typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf