diff options
Diffstat (limited to 'files/ar/web/javascript/reference')
38 files changed, 7936 insertions, 0 deletions
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 +--- +<div>{{jsSidebar("Classes")}}</div> + +<p dir="rtl">الـ <code>constructor</code> هي ميثود خاصة لإنشاء وتهيئة الاوبجكت(كائن) داخل (فئة)<code>class</code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</div> + + + +<h2 dir="rtl" id="بناء_الجملة">بناء الجملة</h2> + +<pre class="syntaxbox">constructor([arguments]) { ... }</pre> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">يمكننا إستخدام تلك الميثود لمرة واحده فقط ، وفي حال إستخدمنا <code>constructor</code> ﻷكثر من مرة في نفس الفئة الـ class سيحدث {{jsxref("SyntaxError")}} إيرور .</p> + +<p>A constructor can use the <code>super</code> keyword to call the constructor of a parent class.</p> + +<p dir="rtl">إذا لم تحدد ميثود إنشاء سيتم تحديد منشئ بشكل تلقائي.</p> + +<p><br> + <sup>If you do not specify a constructor method, a default constructor is used.</sup></p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="إٍستخدام_الميثود_(اسلوب)_الـconstructor">إٍستخدام الميثود (اسلوب) الـ<code>constructor </code></h3> + +<p dir="rtl">ذلك الكود تم أخذه ولصقة من <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>)</p> + +<pre class="brush: js">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; + } +}</pre> + +<h3 dir="rtl" id="مثال_آخر">مثال آخر</h3> + +<p dir="rtl">إنظر إلى ذلك الكود</p> + +<pre class="brush: js">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</pre> + +<p dir="rtl">هنا البروتوتيب فئة الـ <strong>Square</strong> تغيرت ولكن الكونستركتور (المنشئ) مبني على فئة الـ<strong>Polygon </strong>والتي تطلب عندما نقوم بإنشاء حالة مماثلة للـ <strong>Square </strong>مرة أخرى</p> + +<h3 dir="rtl" id="الإنشاء_الإفتراضي">الإنشاء الإفتراضي</h3> + +<p dir="rtl">ذكرنا سابقا أنه في حال عدم تحديدك لكونستركتور (منشئ) سيتم تحديد الكونستركتور بشكل إفتراضي ، وبالنسبة للكلاسز (الفئات) الاولية يكون الكونستركتور الخاص بها كما يلي :-</p> + +<pre class="brush: js">constructor() {} +</pre> + +<p dir="rtl">أما الفئات المشتقة فتكون بالشكل التالي</p> + +<pre class="brush: js">constructor(...args) { + super(...args); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="دعم_المتصفحات">دعم المتصفحات</h2> + + + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="أنظر_أيضا">أنظر أيضا</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> 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 +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax <strong>does not</strong> introduce a new object-oriented inheritance model to JavaScript.</p> + +<h2 id="Defining_classes">Defining classes</h2> + +<p>Classes are in fact "special <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a>", and just as you can define <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a>, the class syntax has two components: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class declarations</a>.</p> + +<h3 id="Class_declarations">Class declarations</h3> + +<p>One way to define a class is using a <strong>class declaration</strong>. To declare a class, you use the <code>class</code> keyword with the name of the class ("Rectangle" here).</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p>An important difference between <strong>function declarations</strong> and <strong>class declarations</strong> 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")}}:</p> + +<pre class="brush: js example-bad">var p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Class_expressions">Class expressions</h3> + +<p>A <strong>class expression</strong> 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) <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">.name</a> property, though)</p> + +<pre class="brush: js">// 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" +</pre> + +<p><strong>Note:</strong> Class <strong>expressions</strong> also suffer from the same hoisting issues mentioned for Class <strong>declarations</strong>.</p> + +<h2 id="Class_body_and_method_definitions">Class body and method definitions</h2> + +<p>The body of a class is the part that is in curly brackets <code>{}</code>. This is where you define class members, such as methods or constructor.</p> + +<h3 id="Strict_mode">Strict mode</h3> + +<p>The bodies of <em>class declarations</em> and <em>class expressions</em> are executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.</p> + +<h3 id="Constructor">Constructor</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> method is a special method for creating and initializing an object created with a <code>class</code>. 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 <code>constructor</code> method.</p> + +<p>A constructor can use the <code>super</code> keyword to call the constructor of the super class.</p> + +<h3 id="Prototype_methods">Prototype methods</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p> + +<pre class="brush: js">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</pre> + +<h3 id="Static_methods">Static methods</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> keyword defines a static method for a class. Static methods are called without <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating </a>their class and <strong>cannot </strong>be called through a class instance. Static methods are often used to create utility functions for an application.</p> + +<pre class="brush: js">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</pre> + +<h3 id="Boxing_with_prototype_and_static_methods">Boxing with prototype and static methods</h3> + +<p>When a static or prototype method is called without a value for <em>this</em>, the <em>this</em> value will be <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.498039);">undefined</span></font> inside the method. This behavior will be the same even if the <code>"use strict"</code> directive isn't present, because code within the <code>class</code> syntax is always executed in strict mode.</p> + +<pre class="brush: js">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</pre> + +<p>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 <em>this</em> value. If the inital value is <code>undefined</code>, <em>this</em> will be set to the global object.</p> + +<p>Autoboxing will not happen in strict mode, the <em>this</em> value remains as passed.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Instance_properties">Instance properties</h3> + +<p>Instance properties must be defined inside of class methods:</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<p>Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration:</p> + +<pre class="brush: js">Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25; +</pre> + +<p> </p> + +<h2 id="Sub_classing_with_extends">Sub classing with <code>extends</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> keyword is used in <em>class declarations</em> or <em>class expressions</em> to create a class as a child of another class.</p> + +<pre class="brush: js">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. +</pre> + +<p>If there is a constructor present in subclass, it needs to first call super() before using "this".</p> + +<p>One may also extend traditional function-based "classes":</p> + +<pre class="brush: js">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. +</pre> + +<p>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()")}}:</p> + +<pre class="brush: js">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. +</pre> + +<h2 id="Species">Species</h2> + +<p>You might want to return {{jsxref("Array")}} objects in your derived array class <code>MyArray</code>. The species pattern lets you override default constructors.</p> + +<p>For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent <code>Array</code> object, instead of the <code>MyArray</code> object. The {{jsxref("Symbol.species")}} symbol lets you do this:</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Super_class_calls_with_super">Super class calls with <code>super</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> keyword is used to call corresponding methods of super class.</p> + +<pre class="brush: js">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. + +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>Abstract subclasses or <em>mix-ins</em> 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.</p> + +<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p> + +<pre class="brush: js">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>A class that uses these mix-ins can then be written like this:</p> + +<pre class="brush: js">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="Running_in_Scratchpad">Running in Scratchpad</h2> + +<p>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>.</p> + +<p>To re-run a definition, use Scratchpad's menu Execute > Reload and Run.<br> + Please vote for bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">#1428672</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> + <li><a href="https://github.com/tc39/proposal-class-fields">Fields and public/private class properties proposal (stage 3)</a></li> +</ul> 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 +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>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 <code>name</code> and a <code>message</code>.</p> + +<p>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.</p> + +<h2 id="List_of_errors">List of errors</h2> + +<p>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!</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> +</ul> 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 +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="الرسالة">الرسالة</h2> + +<pre class="syntaxbox">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 +</pre> + +<h2 id="نوع_الخطأ">نوع الخطأ</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="ماذا_حصل؟"> ماذا حصل؟</h2> + +<p>خطأ غير متوقع، يحدث كثيرا مع {{jsxref("undefined")}} أو قيم {{jsxref("null")}} .</p> + +<p>أيضا في بعض الوضائف مثل {{jsxref("Object.create()")}} أو {{jsxref("Symbol.keyFor()")}}, تحتاج تقديد أنواع محددة.</p> + +<h2 id="أمثلة">أمثلة</h2> + +<h3 id="حالات_غير_صحيحة">حالات غير صحيحة</h3> + +<pre class="brush: js example-bad">// 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 +</pre> + +<h3 class="highlight-spanned" id="حل_المشكلة"><span class="highlight-span"><span class="notranslate">حل المشكلة</span> </span></h3> + +<p><span class="notranslate">لإصلاح مؤشر null إلى قيم <code>undefined</code> أو <code>null</code> ، يمكنك استخدام عامل التشغيل <a href="https://translate.googleusercontent.com/translate_c?act=url&depth=1&hl=ar&ie=UTF8&prev=_t&rurl=translate.google.com&sl=auto&sp=nmt4&tl=ar&u=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof&xid=17259,1500002,15700002,15700021,15700124,15700149,15700186,15700190,15700201,15700214&usg=ALkJrhh23enjQBtOCeYxpsucdSXvqqK0dg">typeof</a> ، على سبيل المثال.</span></p> + +<pre class="brush: js">if (typeof foo !== 'undefined') { + // الآن نعلم أن القيمة المدخلة غير محددة، نستطيع القيام بأي إجراء بدون خطأ. +}</pre> + +<h2 id="شاهد_أيضاً">شاهد أيضاً</h2> + +<ul> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<div dir="rtl">كائن <strong>Array</strong> في جافاسكربت هو كائن عام، يستخدم في إنشاء المصفوفات، وهي تشبه قائمة من الكائنات عالية المستوى.</div> + +<div dir="rtl"> </div> + +<p dir="rtl"><strong>إنشاء مصفوفة</strong></p> + +<pre class="brush: js">var fruits = ["Apple", "Banana"]; + +console.log(fruits.length); +// 2 +</pre> + +<p dir="rtl"><strong>الوصول إلى عنصر محدد في المصفوفة</strong></p> + +<pre class="brush: js">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p dir="rtl"><strong>تنفيذ حلقة تكرار على مصفوفة</strong></p> + +<pre class="brush: js">fruits.forEach(function (item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p dir="rtl"><strong>إلحاق عنصر بآخر المصفوفة</strong></p> + +<pre class="brush: js">var newLength = fruits.push("Orange"); +// ["Apple", "Banana", "Orange"] +</pre> + +<p dir="rtl"><strong>حذف عنصر من نهاية المصفوفة</strong></p> + +<pre class="brush: js">var last = fruits.pop(); // remove Orange (from the end) +// ["Apple", "Banana"]; +</pre> + +<p dir="rtl"><strong>حذف عنصر من بداية المصفوفة</strong></p> + +<pre class="brush: js">var first = fruits.shift(); // remove Apple from the front +// ["Banana"]; +</pre> + +<p dir="rtl"><strong>إضافة عنصر إلى بداية المصفوفة</strong></p> + +<pre class="brush: js">var newLength = fruits.unshift("Strawberry") // add to the front +// ["Strawberry", "Banana"]; +</pre> + +<p dir="rtl"><strong>الوصول إلى ترتيب عنصر معينة في المصفوفة</strong></p> + +<pre class="brush: js">fruits.push("Mango"); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf("Banana"); +// 1 +</pre> + +<p dir="rtl"><strong>حذف عنصر عن طريق ترتيبه في المصفوفة</strong></p> + +<pre class="brush: js">var removedItem = fruits.splice(pos, 1); // this is how to remove an item +// ["Strawberry", "Mango"] +</pre> + +<p dir="rtl"><strong>نسخة مصفوفة</strong></p> + +<pre class="brush: js">var shallowCopy = fruits.slice(); // this is how to make a copy +// ["Strawberry", "Mango"] +</pre> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] +new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) +new Array(<var>arrayLength</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the <code>Array</code> 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 <code>Array</code> constructor, not array literals created with the bracket syntax.</dd> + <dt><code>arrayLength</code></dt> + <dd>If the only argument passed to the <code>Array</code> constructor is an integer between 0 and 2<sup>32</sup>-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.</dd> +</dl> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p>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.</p> + +<p>Some people think that <a class="external" href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/">you shouldn't use an array as an associative array</a>. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post <a class="external" href="http://www.less-broken.com/blog/2010/12/lightweight-javascript-dictionaries.html">Lightweight JavaScript dictionaries with arbitrary keys</a> as an example.</p> + +<h3 dir="rtl" id="الوصول_إلى_عناصر_المصفوفة">الوصول إلى عناصر المصفوفة</h3> + +<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.</p> + +<pre class="brush: js">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' +</pre> + +<p>Array elements are object properties in the same way that <code>toString</code> 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:</p> + +<pre class="brush: js">console.log(arr.0); // a syntax error +</pre> + +<p>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 <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> + +<pre class="brush: js">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // a syntax error +console.log(years[0]); // works properly +</pre> + +<pre class="brush: js">renderer.3d.setTexture(model, 'character.png'); // a syntax error +renderer['3d'].setTexture(model, 'character.png'); // works properly +</pre> + +<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is for this reason that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> + +<pre class="brush: js">console.log(years['2'] != years['02']); +</pre> + +<p>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):</p> + +<pre class="brush: js">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['array']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> + +<p>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.</p> + +<pre class="brush: js">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>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:</p> + +<pre class="brush: js">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>Increasing the {{jsxref("Array.length", "length")}}.</p> + +<pre class="brush: js">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> + +<pre class="brush: js">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>This is explained further on the {{jsxref("Array.length")}} page.</p> + +<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> + +<p>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:</p> + +<pre class="brush: js">// 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'); +</pre> + +<p>The properties and elements returned from this match are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Property/Element</td> + <td class="header">Description</td> + <td class="header">Example</td> + </tr> + <tr> + <td><code>input</code></td> + <td>A read-only property that reflects the original string against which the regular expression was matched.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>A read-only property that is the zero-based index of the match in the string.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>A read-only element that specifies the last matched characters.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="الخصائص">الخصائص</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 dir="rtl" id="الدوال">الدوال</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Returns true if a variable is an array, if not false.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 dir="rtl" id="الخصائص_2">الخصائص</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 dir="rtl" id="الدوال_2">الدوال</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<div class="warning"> +<p><strong>Array generics are non-standard, deprecated and will get removed near future</strong>. Note that you can not rely on them cross-browser. However, there is a <a href="https://github.com/plusdude/array-generics">shim available on GitHub</a>.</p> +</div> + +<p>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 <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> + +<p>These are <strong>not</strong> 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:</p> + +<pre class="brush: js">// 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]); + } +}()); +</pre> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="إنشاء_مصفوفة">إنشاء مصفوفة</h3> + +<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> + +<pre class="brush: js">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 dir="rtl" id="إنشاء_مصفوفة_ذات_بعدين">إنشاء مصفوفة ذات بعدين</h3> + +<p>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.</p> + +<pre class="brush: js">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')); +</pre> + +<p dir="rtl">هذه هي النتيجة (الخرج):</p> + +<pre class="eval">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 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>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")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>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")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="التوافق_مع_المتصفحات">التوافق مع المتصفحات</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 dir="rtl" id="إقرأ_أيضا">إقرأ أيضا</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p dir="rtl"><code><strong>()Array.isArray</strong></code> تفحص القيمة التي تم تمريرها هل هي {{jsxref("Array")}} أم ﻻ.</p> + +<h2 dir="rtl" id="بنية_الجملة">بنية الجملة</h2> + +<pre class="syntaxbox"><code>Array.isArray(<em>value</em>)</code></pre> + +<h3 dir="rtl" id="المعلمات">المعلمات</h3> + +<dl> + <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">value</span></font></dt> + <dd dir="rtl">القيمة التي سيتم فحصها.</dd> +</dl> + +<h3 dir="rtl" id="القيمة_العائدة">القيمة العائدة</h3> + +<p dir="rtl">تكون القيمة العائدة <code>true</code> إذا كانت {{jsxref("Array")}}؛ وتكون <code>false</code> إذا كانت غير ذلك.</p> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">إذا كانت القيمة {{jsxref("Array")}}, <code>true</code> ستكون القيمة العائدة؛ غير ذلك ستكون <code>false</code>.</p> + +<p dir="rtl"><span style="line-height: 1.5;">لمزيد من التفاصيل، راجع هذا المقال </span><a href="http://web.mit.edu/jwalden/www/isArray.html" style="line-height: 1.5;">“Determining with absolute accuracy whether or not a JavaScript object is an array”</a><span style="line-height: 1.5;"> .</span></p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<pre class="brush: js">//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 }); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Running the following code before any other code will create <code>Array.isArray()</code> if it's not natively available.</p> + +<pre class="brush: js">if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} +</pre> + +<h2 dir="rtl" id="المواصفات">المواصفات</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="التكامل_مع_المتصفحات">التكامل مع المتصفحات</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 dir="rtl" id="إقرأ_أيضا">إقرأ أيضا</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p dir="rtl">دالة <code><strong>()join </strong></code>تقوم بدمج جميع عناصر المصفوفة في نص واحد.</p> + +<pre class="brush: js">var a = ['Wind', 'Rain', 'Fire']; +a.join(); // 'Wind,Rain,Fire' +a.join('-'); // 'Wind-Rain-Fire'</pre> + +<h2 dir="rtl" id="صيغة_الكتابة">صيغة الكتابة</h2> + +<pre class="syntaxbox" dir="rtl"><code><var>str</var> = <var>arr</var>.join([<var>separator</var> = ','])</code></pre> + +<h3 id="المعاملات">المعاملات</h3> + +<dl> + <dt><code>separator</code></dt> + <dd dir="rtl">اختياري. يحدد النص الذي سيقوم بفصل عناصر المصفوفة عن بعضهم البعض. الـ <strong>separator</strong> سيتحول إلى جزء من النص الناتج. إذا لم يتم تمريره، سيتم الفصل بين عناصر المصفوفة بالـ comma. إذا كان الـ<strong>separator</strong> عبارة عن نص فارغ، سيتم ضم عناصر المصفوفة دون أي فاصل</dd> +</dl> + +<h3 dir="rtl" id="القيمة_العائدة">القيمة العائدة</h3> + +<p dir="rtl">عناصر المصفوفة مضمومين في هيئة نص.</p> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">تقوم بدمج عناصر المصفوفة في هيئة نص، إذا كان أحد هذه العناصر قيمة فارغة أو غير معرف سيتم تحويله إلى نص فارغ.</p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="ضم_عناصر_المصفوفة_بأربعة_طرق_مختلفة">ضم عناصر المصفوفة بأربعة طرق مختلفة</h3> + +<p dir="rtl">المثال التالي يقوم بإنشاء مصفوفة a ، بها ثلاثة عناصر، ثم يقوم بضم هذه العناصر الثلاثة، ثم يقوم بضم هذه العناصر الثلاثة إلى نص واحد بأربعة طرق: استخدام الـ separator الإفتراضي، ثم باستخدام الـ comma والمسافة، ثم باستخدام علامة الجمع وأخيرا باستخدام نص فارغ.</p> + +<pre class="brush: js">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' تسند +</pre> + +<h2 dir="rtl" id="المواصفات">المواصفات</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">الصفة</th> + <th dir="rtl" scope="col">الحالة</th> + <th scope="col">تعليق</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="التكامل_مع_المتصفحات">التكامل مع المتصفحات</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 dir="rtl" id="إقرأ_أيضا">إقرأ أيضا</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> 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 +--- +<div dir="rtl">{{JSRef}}<br> + دالة <code><strong>pop() </strong></code>هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاعه</div> + +<div dir="rtl"> </div> + +<h2 dir="rtl" id="Syntax">Syntax</h2> + +<pre class="syntaxbox" dir="rtl"><var>arr</var>.pop()</pre> + +<h3 dir="rtl" id="قيمة_الإرجاع">قيمة الإرجاع</h3> + +<p dir="rtl">تعيد أخر عنصر من المصفوفة و تعيد {{jsxref("undefined")}} في حال كانت المصفوفة فارغة</p> + +<h2 dir="rtl" id="وصف">وصف</h2> + +<p dir="rtl"> دالة POP هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاع تلك القيمة إلى الطالب </p> + +<p dir="rtl"><code>pop</code> 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 <code>length</code> property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.</p> + +<p dir="rtl"> في حالة استدعائك لدالة POP على مصفوفة فارغة فسيتم إرجاع {{jsxref("undefined")}} </p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="إزالة_العنصر_الأخير_من_المصفوفة">إزالة العنصر الأخير من المصفوفة</h3> + +<p dir="rtl">التعليمة البرمجية التالية : تقوم بإنشاء مصفوفة(<code>myFish</code> ) تحتوي على أربعة عناصر ثم تقوم بمسح أخر عنصر </p> + +<pre class="brush: js" dir="rtl">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'</pre> + +<h2 dir="rtl" id="مواصفات">مواصفات</h2> + +<table class="standard-table" dir="rtl"> + <tbody> + <tr> + <th scope="col">مواصفات</th> + <th scope="col">الحالة</th> + <th scope="col">تعليق</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="Browser_compatibility">Browser compatibility</h2> + +<div dir="rtl">{{CompatibilityTable}}</div> + +<div dir="rtl" id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div dir="rtl" id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 dir="rtl" id="See_also">See also</h2> + +<ul> + <li dir="rtl">{{jsxref("Array.prototype.push()")}}</li> + <li dir="rtl">{{jsxref("Array.prototype.shift()")}}</li> + <li dir="rtl">{{jsxref("Array.prototype.unshift()")}}</li> + <li dir="rtl">{{jsxref("Array.prototype.splice()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p dir="rtl">دالة الـ <code><strong>()reverse</strong></code> تقوم بعكس ترتيبا عناصر المصفوفة مكانيا، بحيث يصبح العنصر الأول في المصفوفة في آخر المصفوفة، ويكون آخر عنصر فيها في أول المصفوفة.</p> + +<h2 dir="rtl" id="صيغة_الكتابة">صيغة الكتابة</h2> + +<pre class="syntaxbox"><code><var>arr</var>.reverse()</code></pre> + +<h3 dir="rtl" id="القيمة_العائدة">القيمة العائدة</h3> + +<p dir="rtl">المصفوفة المعكوسة.</p> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p>The <code>reverse</code> method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.</p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="عكس_العناصر_في_مصفوفة">عكس العناصر في مصفوفة</h3> + +<p dir="rtl">المثال التالي يقوم بإنشاء مصفوفة myArray تحتوي على ثلاثة عناصر، ثم يوم بعكس المصفوفة.</p> + +<pre class="brush: js">var myArray = ['one', 'two', 'three']; +myArray.reverse(); + +console.log(myArray) // ['three', 'two', 'one'] +</pre> + +<h2 dir="rtl" id="المواصفات">المواصفات</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th dir="rtl" scope="col">المواصفة</th> + <th scope="col">الحالة</th> + <th scope="col">تعليق</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="التكامل_مع_المتصفحات">التكامل مع المتصفحات</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 dir="rtl" id="إقرأ_أيضا">إقرأ أيضا</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p dir="rtl">ال <code><strong>slice()</strong></code> method إرجاع نسخة ضئيلة من جزء من مصفوفة إلى object مصفوفة جديد تم تحديده من <code>start</code> إلى <code>end</code> (<code>end</code> غير مضمنة) بينما <code>start</code> و <code>end</code> تمثلان مؤشر العناصر في هذه المصفوفة. لن يتم تعديل المصفوفة الأصلية.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 dir="rtl" id="تركيب_الجملة">تركيب الجملة</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.slice([<var>start</var>[, <var>end</var>]]) +</pre> + +<h3 dir="rtl" id="المعاملات">المعاملات</h3> + +<dl> + <dt><code><var>start</var></code> {{optional_inline}}</dt> + <dd dir="rtl">مؤشر ذو أساس صفري يبدأ فيه الاستخراج.</dd> + <dd dir="rtl">يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. <code>slice(-2)</code> يستخرج آخر عنصرين في التسلسل.</dd> + <dd dir="rtl">إذا كانت <code><var>start</var></code> غير محددة, تبدأ<code>slice</code> من المؤشر <code>0</code>.</dd> + <dd dir="rtl">إذا كانت <code><var>start</var></code> is أكبر من نطاق فهرس التسلسل ، يتم إرجاع صفيف فارغ.</dd> + <dt><code><var>end</var></code> {{optional_inline}}</dt> + <dd dir="rtl">مؤشر ذو أساس صفري قبل أن ينتهي الاستخراج. <code>slice</code> مستخرجات إلى ولا تشمل <code><var>end</var></code>. على سبيل المثال, <code>slice(1,4)</code> يستخرج العنصر الثاني من خلال العنصر الرابع (العناصر المفهرسة 1 و 2 و 3).</dd> + <dd dir="rtl">يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. <code>slice(2,-1)</code> يستخرج العنصر الثالث من خلال العنصر الثاني إلى الأخير في التسلسل.</dd> + <dd dir="rtl">إذا تم حذف <code><var>end</var></code>, <code>slice</code> مستخرجات من خلال نهاية التسلسل(<code><var>arr</var>.length</code>).</dd> + <dd dir="rtl">اذا كانت <code><var>end</var></code> أكبر من طول التسلسل, فإن<code>slice</code> تستخرج حتى نهاية التسلسل(<code><var>arr</var>.length</code>).</dd> +</dl> + +<h3 id="القيمة_العائدة">القيمة العائدة</h3> + +<p dir="rtl">مصفوفة جديدة تحتوي على العناصر المستخرجة.</p> + +<h2 id="الوصف">الوصف</h2> + +<p dir="rtl"><code>slice</code> لا تغير المصفوفة الأصلية. تقوم بإرجاع نسخة ضئيلة من العناصر من المصفوفة الأصلية. يتم نسخ عناصر الصفيف الأصلي في الصفيف الذي تم إرجاعه كما يلي:</p> + +<ul> + <li dir="rtl">للreference Object(وليس الobject الفعلي) ،تقوم <code>slice</code> بنسخ reference object إلى المصفوفة الجديدة الجديد. يشير كل من المصفوفة الأصلية والجديدة إلى نفس ال object. إذا تغير reference Object ، تكون التغييرات مرئية لكل من المصفوفات الجديدة والأصلية.</li> + <li dir="rtl">للأرقام و الحروف والقيم المنطقية strings, numbers and booleans (not {{jsxref("String")}}, {{jsxref("Number")}} and {{jsxref("Boolean")}} objects),تقوم <code>slice</code> بنسخ القيم إلى مصفوفة جديدة. لا تؤثر التغييرات على الحرف أو الرقم أو القيمة المنطقية في مصفوفة على المصفوفة الآخرى.</li> +</ul> + +<p dir="rtl">إذا تمت إضافة عنصر جديد إلى أي مصفوفة ، فلن تتأثر المصفوفة الآخرى.</p> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="إعادة_جزء_من_من_مصفوفة_موجودة">إعادة جزء من من مصفوفة موجودة</h3> + +<pre class="brush: js notranslate">let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +let citrus = fruits.slice(1, 3) + +// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus contains ['Orange','Lemon'] +</pre> + +<h3 dir="rtl" id="باستخدام_slice">باستخدام <code>slice</code></h3> + +<p dir="rtl">في المثال التالي, تقوم<code>slice</code> بإنشاء مصفوفة جديدة <code>newCar</code>, من <code>myCar</code>. كلاهما يتضمن إشارة إلى الobject <code>myHonda</code>. عندما يتغير لون <code>myHonda</code> إلى الأرجواني, تعكس كلا المصفوفتان التغيير.</p> + +<pre class="brush: js notranslate">// 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) +</pre> + +<p>This script writes:</p> + +<pre class="notranslate">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 +</pre> + +<h3 id="Array-like_objects">Array-like objects</h3> + +<p dir="rtl"><code>slice</code> method يمكن أيضًا استدعاؤها لتحويل Array-like objects / مجموعات إلى مصفوفة جديدة. انت فقط {{jsxref("Function.prototype.bind", "bind")}} the method لل object. The {{jsxref("Functions/arguments", "arguments")}}داخل دالة هو مثال على 'array-like object'.</p> + +<pre class="brush: js notranslate">function list() { + return Array.prototype.slice.call(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3] +</pre> + +<p>البناء يمكن أن يتم ب {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} ويمكن تقليلها باستخدام <code>[].slice.call(arguments)</code> بدلا من<code>Array.prototype.slice.call</code>.</p> + +<p dir="rtl">على أي حال يمكن تبسيطها باستخدام {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js notranslate">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]</pre> + +<h2 id="المواصفات">المواصفات</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">مواصفات</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="التوافق_مع_المتصفح">التوافق مع المتصفح</h2> + +<div class="hidden">يتم إنشاء جدول التوافق في هذه الصفحة من البيانات المهيكلة. إذا كنت ترغب في المساهمة في البيانات ، يرجى مراجعة https://github.com/mdn/browser-compat-data وإرسال طلب سحب إلينا.</div> + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> + +<h2 id="انظر_أيضا">انظر أيضا</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>دالة <code>getDate()</code> تقوم بإرجاع يوم من تاريخ الشهر المحدد وفقاً للوقت المحلي.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getdate.html")}}</div> + + + +<h2 id="بنية_الجملة">بنية الجملة</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getDate()</code> +</pre> + +<h3 id="القيمة_العائدة">القيمة العائدة</h3> + +<p>رقم صحيح ما بين 1 و31 يمثل يوم محدد من تاريخ الشهر المحدد وفقاً للوقت المحلي.</p> + +<h2 id="أمثلة">أمثلة</h2> + +<h3 id="استخدام_getDate()">استخدام <code>getDate()</code></h3> + +<p>البيان الثاني قام بتعيين قيمة المتغير <code>day</code>، علي أساس قيمة تاريخ المتغير <code>Xmas95</code>.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var day = Xmas95.getDate(); + +console.log(day); // 25 +</pre> + +<h2 id="الخصائص">الخصائص</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="دعم_المتصفحات">دعم المتصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.getDate")}}</p> + +<h2 id="اقرأ_أيضًا">اقرأ أيضًا</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> + <li>{{jsxref("Date.prototype.setDate()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>Creates a JavaScript <strong><code>Date</code></strong> instance that represents a single moment in time. <code>Date</code> objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.</p> + +<h2 id="البنيه">البنيه</h2> + +<pre class="syntaxbox"><code>new Date(); +new Date(<var>value</var>); +new Date(<var>dateString</var>); +new Date(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minutes</var>[, <var>seconds</var>[, <var>milliseconds</var>]]]]]); +</code></pre> + +<div class="note"> +<p><strong>Note:</strong> JavaScript <code>Date</code> objects can only be instantiated by calling JavaScript <code>Date</code> 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 <code>Date</code> object; unlike other JavaScript object types, JavaScript <code>Date</code> objects have no literal syntax.</p> +</div> + +<h3 id="Parameters">Parameters</h3> + +<div class="note"> +<p><strong>Note:</strong> Where <code>Date</code> 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. <code>new Date(2013, 13, 1)</code> is equivalent to <code>new Date(2014, 1, 1)</code>, both create a date for <code>2014-02-01</code> (note that the month is 0-based). Similarly for other values: <code>new Date(2013, 2, 1, 0, 70)</code> is equivalent to <code>new Date(2013, 2, 1, 1, 10)</code> which both create a date for <code>2013-03-01T01:10:00</code>.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Where <code>Date</code> is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use <code>new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}})</code> with the same arguments.</p> +</div> + +<dl> + <dt><code>value</code></dt> + <dd>Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).</dd> + <dt><code>dateString</code></dt> + <dd>String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (<a href="http://tools.ietf.org/html/rfc2822#page-14">IETF-compliant RFC 2822 timestamps</a> and also a <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">version of ISO8601</a>). + <div class="note"> + <p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p> + </div> + </dd> + <dt><code>year</code></dt> + <dd>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")}}.</dd> + <dt><code>month</code></dt> + <dd>Integer value representing the month, beginning with 0 for January to 11 for December.</dd> + <dt><code>day</code></dt> + <dd>Optional. Integer value representing the day of the month.</dd> + <dt><code>hour</code></dt> + <dd>Optional. Integer value representing the hour of the day.</dd> + <dt><code>minute</code></dt> + <dd>Optional. Integer value representing the minute segment of a time.</dd> + <dt><code>second</code></dt> + <dd>Optional. Integer value representing the second segment of a time.</dd> + <dt><code>millisecond</code></dt> + <dd>Optional. Integer value representing the millisecond segment of a time.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<ul> + <li>If no arguments are provided, the constructor creates a JavaScript <code>Date</code> object for the current date and time according to system settings.</li> + <li>If at least two arguments are supplied, missing arguments are either set to 1 (if day is missing) or 0 for all others.</li> + <li>The JavaScript date is based on a time value that is milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript <code>Date</code> object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.</li> + <li>The JavaScript <code>Date</code> object provides uniform behavior across platforms. The time value can be passed between systems to represent the same moment in time and if used to create a local date object, will reflect the local equivalent of the time.</li> + <li>The JavaScript <code>Date</code> object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.</li> + <li>Invoking JavaScript <code>Date</code> as a function (i.e., without the {{jsxref("Operators/new", "new")}} operator) will return a string representing the current date and time.</li> +</ul> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("Date.prototype")}}</dt> + <dd>Allows the addition of properties to a JavaScript <code>Date</code> object.</dd> + <dt><code>Date.length</code></dt> + <dd>The value of <code>Date.length</code> is 7. This is the number of arguments handled by the constructor.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Date.now()")}}</dt> + <dd>Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.</dd> + <dt>{{jsxref("Date.parse()")}}</dt> + <dd>Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. + <div class="note"> + <p><strong>Note:</strong> Parsing of strings with <code>Date.parse</code> is strongly discouraged due to browser differences and inconsistencies.</p> + </div> + </dd> + <dt>{{jsxref("Date.UTC()")}}</dt> + <dd>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.</dd> +</dl> + +<h2 id="JavaScript_Date_instances">JavaScript <code>Date</code> instances</h2> + +<p>All <code>Date</code> instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the <code>Date</code> constructor can be modified to affect all <code>Date</code> instances.</p> + +<h3 id="Date.prototype_Methods">Date.prototype Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Several_ways_to_create_a_Date_object">Several ways to create a <code>Date</code> object</h3> + +<p>The following examples show several ways to create JavaScript dates:</p> + +<div class="note"> +<p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p> +</div> + +<pre class="brush: js">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); +</pre> + +<h3 id="Two_digit_years_map_to_1900_-_1999">Two digit years map to 1900 - 1999</h3> + +<p>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.</p> + +<pre class="brush: js">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) +</pre> + +<h3 id="Calculating_elapsed_time">Calculating elapsed time</h3> + +<p>The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.</p> + +<p>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.</p> + +<pre class="brush: js">// 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 +</pre> + +<pre class="brush: js">// 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 +</pre> + +<pre class="brush: js">// 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); +</pre> + +<div class="note"> +<p><strong>Note:</strong> 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()")}}.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [2]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Some browsers can have issues when parsing dates: <a href="http://dygraphs.com/date-formats.html">3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings</a></p> + +<p>[2] <a href="https://msdn.microsoft.com/en-us//library/ie/ff743760(v=vs.94).aspx">ISO8601 Date Format is not supported</a> in Internet Explorer 8, and other version can have <a href="http://dygraphs.com/date-formats.html">issues when parsing dates</a></p> 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 +--- +<div>{{JSRef}}</div> + +<p>تقوم دالة <strong><code>Date.now()</code></strong> بعرض عدد الثواني التي مضت منذ بداية احتساب الوقت بطريقة Timestamp وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تمامًا (First of January 1970 00:00:00) بتوقيت UTC.</p> + +<h2 id="بنية_الجملة">بنية الجملة</h2> + +<pre class="syntaxbox"><code>var timeInMs = Date.now();</code></pre> + +<h3 id="القيمة_الراجعة">القيمة الراجعة</h3> + +<p>القيمة الراجعة من هذه الدالة ستكون عبارة عن رقم {{jsxref("Number")}}، هذا الرقم يشير إلى عدد الثواني التي انقضت منذ بداية احتساب الوقت بطريقة TimeStamp بالأنظمة التي تستند إلى UNIX.</p> + +<h2 id="الوصف">الوصف</h2> + +<p>لإن دالة <code>now()</code> تقوم بإرجاع قيمة ثابتة من الوقت {{jsxref("Date")}} فيجب عليك استخدامها بهذا الشكل <code>Date.now()</code> .</p> + +<h2 id="طريقة_احتياطية_(Polyfill)">طريقة احتياطية (Polyfill)</h2> + +<p>تم اعتماد هذه الدالة في إصدار ECMA-262 5<sup>th</sup> المحركات التي لم يتم تحديثها لتدعم هذه الدالة يمكنها أن تحاكي دالة <code>Date.now()</code> عبر استخدام هذه الشيفرة البرمجية، هذه الشيفرة ستسمح للمتصفحات بأن تحاكي وظيفة هذه الدالة في حالة عدم دعمها لها :</p> + +<pre class="brush: js">if (!Date.now) { // إذا لم تكن الدالة موجودة + Date.now = function now() { // قم بإنشاء الدالة + return new Date().getTime(); // واربطها بالوقت الحالي + }; +} +</pre> + +<h2 id="الخصائص">الخصائص</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">الخاصية</th> + <th scope="col">الحالة</th> + <th scope="col">تعليقات</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="دعم_المتصفحات">دعم المتصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.now")}}</p> + +<h2 id="اقرأ_أيضًا">اقرأ أيضًا</h2> + +<ul> + <li>{{domxref("Performance.now()")}} — provides timestamps with sub-millisecond resolution for use in measuring web page performance</li> + <li>{{domxref("console.time()")}} / {{domxref("console.timeEnd()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>تقوم دالة <code>Date.parse()</code> بتوزيع سلسلة من التاريخ، وإرجاع قيمتها إلي مللي ثانية من بداية تاريخ (1 يناير, 1970, 00:00:00 UTC) إلي التاريخ المحدد داخل الأقواس مثل <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Date.parse("التاريخ")</span></font> أو NaN (ليس رقم) إذا كانت السلسلة غير معترف بها (غير صحيحة)، أو في بعض الحالات التي يكون فيها قيم التاريخ غير شرعية (مكتوبة بشكل خاطيء). علي سبيل المثال (2015-02-31).</p> + +<p>It is not recommended to use <code>Date.parse</code> 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).</p> + +<div>{{EmbedInteractiveExample("pages/js/date-parse.html")}}</div> + + + +<h2 id="بنية_الجملة">بنية الجملة</h2> + +<p>استدعاء مباشر:</p> + +<pre class="syntaxbox">Date.parse(<var>dateString</var>)</pre> + +<p>استدعاء ضمني:</p> + +<pre class="syntaxbox">new Date(<var>dateString</var>)</pre> + +<h3 id="المعاملات">المعاملات</h3> + +<dl> + <dt><code>dateString</code></dt> + <dd>النص يمثل <a href="http://tools.ietf.org/html/rfc2822#section-3.3">RFC2822</a> أو (a variant of) تاريخ <a href="https://ar.wikipedia.org/wiki/%D8%A7%D9%8A%D8%B2%D9%88_8601">ISO 8601</a> (قد يتم استخدام تنسيقات أخري، ولكن ربما قد تكون النتائج غير متوقعة).</dd> +</dl> + +<h3 id="القيمة_الراجعة">القيمة الراجعة</h3> + +<p>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.</p> + +<h2 id="الوصف">الوصف</h2> + +<p>تقوم دالة <code>parse()</code> بأخذ سلسلة التاريخ مثل ("Des 25, 1995") وتقوم بإرجاع القيمة إلي المللي ثانية منذ بداية احتساب الوقت وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تماماً (First of January 1970 00:00:00) بتوقيت UTC، حتي الوقت التي قمت بتحديده. وهذه الدالة مفيدة لتعيين قيمة التاريخ استناداً الي قيمة السلسلة، علي سبيل المثال الدمج مع طريقة {{jsxref("Date.prototype.setTime()", "setTime()")}} و {{jsxref("Global_Objects/Date", "Date")}} .</p> + +<p>Given a string representing a time, <code>parse()</code> returns the time value. It accepts the RFC2822 / IETF date syntax (<a href="http://tools.ietf.org/html/rfc2822#section-3.3">RFC2822 Section 3.3</a>), e.g. <code>"Mon, 25 Dec 1995 13:30:00 GMT"</code>. It understands the continental US time zone abbreviations, but for general use, use a time zone offset, for example, <code>"Mon, 25 Dec 1995 13:30:00 +0430"</code> (4 hours, 30 minutes east of the Greenwich meridian).</p> + +<p>GMT and UTC are considered equivalent. The local time zone is used to interpret arguments in <a href="http://tools.ietf.org/html/rfc2822#section-3.3">RFC2822 Section 3.3</a> format that do not contain time zone information.</p> + +<p>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 <code>"2015-10-12 12:00:00"</code> may be parsed to as <code>NaN</code>, UTC or local timezone.</p> + +<h3 dir="ltr" id="ECMAScript_5_دعم_تنسيق_ISO-8601">ECMAScript 5 دعم تنسيق ISO-8601</h3> + +<p>The date time string may be in a simplified <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> format. For example, <code>"2011-10-10"</code> (just date) or <code>"2011-10-10T14:48:00"</code> (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 <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> format, it will be treated as local.</p> + +<p>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 <code>NaN</code>.</p> + +<p>Because <code>parse()</code> is a static method of {{jsxref("Date")}}, it is called as <code>Date.parse()</code> rather than as a method of a {{jsxref("Date")}} instance.</p> + +<h3 id="الاختلافات_في_المنطقة_الزمنية_المفترضة">الاختلافات في المنطقة الزمنية المفترضة</h3> + +<p>Given a date string of <code>"March 7, 2014"</code>, <code>parse()</code> assumes a local time zone, but given an ISO format such as <code>"2014-03-07"</code> 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.</p> + +<h3 id="Fall-back_to_implementation-specific_date_formats">Fall-back to implementation-specific date formats</h3> + +<p>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 <code>Date.parse()</code> to return {{jsxref("NaN")}}.</p> + +<p>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.:</p> + +<pre class="brush: js" dir="rtl">// سلسلة ليست أيزو مع قيم تاريخ صالحة +new Date('23/25/2014'); +</pre> + +<p>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:</p> + +<pre class="brush: js" dir="rtl">// سلسلة أيزو مع قيمة غير صالحة +new Date('2014-25-23').toISOString(); +// يُعيد "RangeError: invalid date" في جميع المتصفحات المتوافقة مع es5 +</pre> + +<p>SpiderMonkey's implementation-specific heuristic can be found in <a href="http://mxr.mozilla.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889"><code>jsdate.cpp</code></a>. The string <code>"10 06 2014"</code> is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6">rough outline</a> on how the parsing works.</p> + +<pre class="brush: js">new Date('10 06 2014'); +</pre> + +<p>will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:</p> + +<pre class="brush: js">new Date('foo-bar 2014').toString(); +// يُعيد: "Invalid Date" *تاريخ غير صالح* + +Date.parse('foo-bar 2014'); +// يُعيد: NaN *ليس رقم* +</pre> + +<h2 id="أمثلة">أمثلة</h2> + +<h3 id="استخدام_Date.parse()">استخدام <code>Date.parse()</code></h3> + +<p>إذا كان <code>IPOdate</code> هو كائن {{jsxref("Date")}} موجود، فيمكن تعيينه إلي 9 أغسطس، 1995 (بالتوقيت المحلي) كما يلي:</p> + +<pre class="brush: js">IPOdate.setTime(Date.parse('Aug 9, 1995'));</pre> + +<p>بعض الأمثلة الأخرى على تحليل سلاسل التاريخ غير القياسية:</p> + +<pre class="brush: js">Date.parse('Aug 9, 1995');</pre> + +<p>يٌعيد <code>807937200000</code> في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');</pre> + +<p>يٌعيد <code>807926400000</code> بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00'); +</pre> + +<p>يٌعيد <code>807937200000</code> في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT'); +</pre> + +<p>يٌعيد <code>0</code> بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00'); +</pre> + +<p>يٌعيد <code>14400000</code> في المنطقة الزمنية GMT-0400، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400'); +</pre> + +<p>يٌعيد <code>14400000</code> بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).</p> + +<h2 id="الخصائص">الخصائص</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Simplified ISO 8601 format added.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="دعم_المتصفحات">دعم المتصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.parse")}}</p> + +<h2 id="ملاحظات_التوافق">ملاحظات التوافق</h2> + +<ul> + <li>Firefox 49 {{geckoRelease(49)}} changed the parsing of 2-digit years to be aligned with the Google Chrome browser instead of Internet Explorer. Now, 2-digit years that are less than <code>50</code> are parsed as 21st century years. For example, <code>04/16/17</code>, previously parsed as April 16, 1917, will be April 16, 2017 now. To avoid any interoperability issues or ambiguous years, it is recommended to use the ISO 8601 format like "2017-04-16" ({{bug(1265136)}}).</li> +</ul> + +<h2 id="اقرأ_أيضًا">اقرأ أيضًا</h2> + +<ul> + <li>{{jsxref("Date.UTC()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>دالة setDate() تقوم بتعين يوم من الـ {{jsxref("Date")}} المحدد نسبه إلي الشهر المحدد.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-setdate.html")}}</div> + + + +<h2 id="بنية_الجملة">بنية الجملة</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setDate(</code>dayValue [رقم اليوم]<code>)</code></pre> + +<h3 id="المعاملات_(Parameters)">المعاملات (Parameters)</h3> + +<dl> + <dt><code>dayValue</code></dt> + <dd>يجب أن يكون عدد صحيح يمثل يوم من الشهر. علي سبيل المثال <code>setDate(15)</code> .</dd> +</dl> + +<h3 id="القيمة_العائدة">القيمة العائدة</h3> + +<p>عدد المللي ثانية بين تاريخ 1 يناير 1970 00:00:00 UTC والتاريخ المحدد (يتغير الـ {{jsxref("Date")}} أيضا بتغير المكان [المنطقة الزمنية]).</p> + +<h2 id="الوصف">الوصف</h2> + +<p>إذا كان <code>dayValue [رقم اليوم]</code> خارج نطاق قيم الشهر المحدد لهذا التاريخ، فأن دالة <code>setDate()</code> ستقوم بتحديد الـ {{jsxref("Date")}} [اليوم] وفقاً لذلك. علي سبيل المثال، إذا تم تحديد <code>dayValue [رقم اليوم]</code> إلي <code>0</code> فسيتم تعيين التاريخ إلي أخر يوم في الشهر السابق.</p> + +<h2 id="أمثلة">أمثلة</h2> + +<h3 id="استخدام_setDate()">استخدام <code>setDate()</code></h3> + +<pre class="brush: js">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 +</pre> + +<h2 id="الخصائص">الخصائص</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.36', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="دعم_المتصفحات">دعم المتصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.setDate")}}</p> + +<h2 id="اقرأ_أيضًا">اقرأ أيضًا</h2> + +<ul> + <li>{{jsxref("Date.prototype.getDate()")}}</li> + <li>{{jsxref("Date.prototype.setUTCDate()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>دالة <strong><code>Date.UTC()</code></strong> تقبل نفس المُعاملات parameters علي الرغم من طول تكوين المنشيء، ويٌعيد التاريخ إلي المللي ثانية من بداية تاريخ 1 يناير, 1970, 00:00:00, التوقيت العالمي.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-utc.html")}}</div> + + + +<h2 id="بنية_الجملة">بنية الجملة</h2> + +<pre class="syntaxbox">Date.UTC(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]])</pre> + +<h3 id="المعاملات_(Parameters)">المعاملات (Parameters)</h3> + +<dl> + <dt><code>year</code></dt> + <dd>سنة كاملة.</dd> + <dt><code>month</code></dt> + <dd>رقم صحيح ما بين 0 و11 يمثل الشهر.</dd> + <dt><code>day</code></dt> + <dd>اختياري. رقم صحيح ما بين 1 و31 يمثل يوم من الشهر.</dd> + <dt><code>hour</code></dt> + <dd>اختياري. رقم صحيح ما بين 0 و23 يمثل الساعات.</dd> + <dt><code>minute</code></dt> + <dd>اختياري. رقم صحيح ما بين 0 و59 يمثل الدقائق.</dd> + <dt><code>second</code></dt> + <dd>اختياري. رقم صحيح ما بين 0 و59 يمثل الثواني.</dd> + <dt><code>millisecond</code></dt> + <dd>اختياري. رقم صحيح ما بين 0 و999 يمثل الميلي ثانية.</dd> +</dl> + +<h3 id="القيمة_العائدة">القيمة العائدة</h3> + +<p>رقم يمثل عدد المللي ثانية في التاريخ المحدد منذ 1 يناير, 1970, 00:00:00، التوقيت العالمي.</p> + +<h2 id="الوصف">الوصف</h2> + +<p>تقوم دالة <code>UTC()</code> بأخذ معاملات (parameters) التاريخ المحددة بفاصلة ثم تُعيدها إلي مللي ثانية بين 1 يناير 1970، 00:00:00 التوقيت العالمي، والوقت الذي حددته.</p> + +<p>يجب عليك تحديد <code>السنة</code> كاملة؛ علي سبيل المثال, 1998. إذا كانت السنة محددة ما بين عام 0 و99، تقوم هذه الطريقة بتحويل السنه إلي سنه في القرن العشرين <code>(1900 + سنة)</code>؛ علي سبيل المثال، إذا حددت 95، فسيتم أستخدام 1995.</p> + +<p>تختلف طريقة <code>UTC()</code> عن منشيء التاريخ بطريقتين.</p> + +<ul> + <li>تستخدم دالة <code>Date.UTC()</code> التوقيت العالمي بدلاً من التوقيت المحلي.</li> + <li>تقوم دالة <code>Date.UTC()</code> بإرجاع قمية الوقت إلي رقم بدلاً من إنشاء تاريخ.</li> +</ul> + +<p>If a parameter you specify is outside of the expected range, the <code>UTC()</code> 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 <code>(year + 1)</code>, and 3 will be used for the month.</p> + +<p>Because <code>UTC()</code> is a static method of {{jsxref("Date")}}, you always use it as <code>Date.UTC()</code>, rather than as a method of a {{jsxref("Date")}} object you created.</p> + +<h2 id="أمثلة">أمثلة</h2> + +<h3 id="استخدام_Date.UTC()">استخدام <code>Date.UTC()</code></h3> + +<p>في المثال التالي يقوم بإنشاء التاريخ بإستخدام UTC بدلاً من التوقيت المحلي:</p> + +<pre class="brush:js">var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0)); +</pre> + +<h2 id="الخصائص">الخصائص</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="دعم_المتصفحات">دعم المتصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.UTC")}}</p> + +<h2 id="ملاحظات_التوافق">ملاحظات التوافق</h2> + +<h3 id="Date.UTC_with_fewer_than_two_arguments"><code>Date.UTC</code> with fewer than two arguments</h3> + +<p>When providing less than two arguments to <code>Date.UTC</code>, {{jsxref("NaN")}} is returned. This behavior is specified in ECMAScript 2017. Engines who weren't supporting this behavior, have been updated (see {{bug(1050755)}}, <a href="https://github.com/tc39/ecma262/pull/642">ecma-262 #642</a>).</p> + +<pre class="brush: js">Date.UTC(); +Date.UTC(1); + +// Safari: NaN +// Chrome/Opera/V8: NaN + +// Firefox <54: non-NaN +// Firefox 54+: NaN + +// IE: non-NaN +// Edge: NaN +</pre> + +<h2 id="اقرأ_أيضاً">اقرأ أيضاً</h2> + +<ul> + <li>{{jsxref("Date.parse()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<div style="font-family: tahoma; font-size: 15px;"> +<p dir="rtl">تُستدعَى الوظيفة <code>()call</code> على دالة، أول argument لهذه الوظيفة هو قيمة <code>this</code> الخاصة بالدالة، وال arguments المتبقية (إن وُجدت)، هي arguments الدالة.</p> + +<div class="note" dir="rtl"> +<p><strong>ملاحظة : </strong> صيغة هذه الوظيفة مماثلة تقريبًا للصيغة الخاصة بـ {{jsxref("Function.prototype.apply", "apply")}} الفرق الوحيد هو ان <strong> </strong><code>()call</code><strong> </strong>تاخذ قائمة من ال <strong>arguments</strong> محددة بشكل فردي فيما تاخذ <code>()apply</code> مصفوفة واحدة من ال <strong>arguments</strong>.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/function-call.html")}}</div> + + + +<h2 dir="rtl" id="صيغة_الوظيفة_call">صيغة الوظيفة call</h2> + +<pre class="syntaxbox notranslate"><code><var>function</var>.call(<var>thisArg</var>, <var>arg1</var>, <var>arg2</var>, ...)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt dir="rtl"><code>thisArg</code></dt> + <dd dir="rtl">اختياري. وهو قيمة <code>this</code> المتوفرة في استدعاء الدالة <code><var>function</var></code>. لاحظ أن <code>this</code> قد لا تكون القيمة الفعلية التي تراها الوظيفة: اذا كانت هذه الوظيفة دالة في {{jsxref("Strict_mode", "non-strict mode", "", 1)}} سيتم استبدال {{jsxref("Global_Objects/null", "null")}} و {{jsxref("Global_Objects/undefined", "undefined")}} بالكائن العام والقيم الاولية ستحول الى كائنات. </dd> + <dt dir="rtl"><code>...,arg1, arg2</code></dt> + <dd dir="rtl"> arguments الدالة <code><var>function</var></code>.</dd> +</dl> + +<h3 dir="rtl" id="Return_value">Return value</h3> + +<p dir="rtl">تُرجع نتيجة استدعاء الدالة مع قيمة <strong> </strong><code>this</code> المحددة و ال arguments.</p> + +<h2 dir="rtl" id="وصف">وصف</h2> + +<p dir="rtl">تسمح الوظيفة <code>()call</code> لدالة او وظيفة خاصة بكائن واحد بان يتم استدعاؤها وتعيينها من قبل كائن مختلف.</p> + +<p dir="rtl">تمنح الوظيفة <code>()call</code> قيمة <code>this</code> الجديدة الى الدالة/الوظيفة. مع الـ <code>call</code> يمكنك كتابة الوظيفة مرة واحدة ومن ثم تقوم بتوريثها لكائن آخر دون الحاجة إلى إعادة كتابة الوظيفة للكائن الجديد.</p> + +<h2 dir="rtl" id="تحليل_الجزء_الغامض_في_الوظيفة_call">تحليل الجزء الغامض في الوظيفة <code>()call</code></h2> + +<p dir="rtl">نظرا لعدم وجود شرح كاف حول هذه الجزئية فقد ارتايت ان اظيف هذه الفقرة التوضيحية لعلها تزيح بعض الغموض عن قيمة ال <code>this</code> التي تمثل ال argument الاول لهذه الوظيفة.</p> + +<p dir="rtl">اذا نظرنا بتمعن في هذا الجزء من داخل الوظيفة <code>call</code>. سنجد ان thisArg ستساوي الكائن العام في حالة undefined او null، والا ستساوي ناتج الكائن Object، تساوي thisArg كائنا في كلتا الحالتين. وعليه فقد اصبحت كائنا، اذن فمن الطبيعي ان تمتلك خصائص. تم تحديد الخاصية _callTemp_ قيمتها this و this تمثل الدالة التي ستستدعى عليها الوظيفة <code>call</code>. واخيرا يتم تنفيذ هذه الدالة:</p> + +<pre class="brush: js notranslate">Function.prototype.call_like = function( thisArg, args ){ + thisArg = ( thisArg === undefined || thisArg === null ) ? window : Object( thisArg ); + thisArg._callTemp_ = this; + thisArg._callTemp_(); +}</pre> + +<p dir="rtl">في حالة عدم وجود thisArg ستتصرف الدالة fn بشكل طبيعي و this ستساوي الكائن العام:</p> + +<pre class="brush: js notranslate">var fn = function () { + console.log( this ); // [object Window] +} +fn.call_like(); + +</pre> + +<p dir="rtl">في حالة وجود thisArg بقيمة اولية ك undefined او null ف this ستساوي ايضا الكائن العام، خلاف ذالك سيتم تمرير قيمتها الى الكائن <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">()</a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>، اذا كانت هذه القيمة من القيم الاولية-<a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive value</a> سيقوم الكائن بتحويلها الى الكائن المناسب لها، واما اذا كانت هذه القيمة كائنا فلا حاجة لتحويلها و this ستساوي كائنا.</p> + +<p dir="rtl">وهذا يفسر كيف قام الكائن Object بتحويل القيمة الاولية <code>"Youssef belmeskine"</code> الى الكائن String: </p> + +<pre class="brush: js notranslate">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" ); + +</pre> + +<p dir="rtl">من المهم دائما ذكر المصدر:</p> + +<div class="blockIndicator note"> +<p dir="rtl">بالنسبة لى شخصيا لم اتمكن من فهم هذه الوظيفة وشقيقتها apply بشكل واضح الا عندما قمت بالاطلاع على الكود الداخلى لها. قمت باستخدام هذا الجزء من الكود لتوضيح الفكرة فقط. ستجد ال Polyfill كاملا في هذا الموقع <a href="https://hexmen.com/blog/2006/12/26/revisiting-functionprototypeapply-for-ie5/">hexmen.com.</a></p> +</div> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="استخدام_ال_call_لِسَلسَلة_منشئات_الكائن">استخدام ال <code>call</code> لِسَلسَلة منشئات الكائن</h3> + +<p dir="rtl">تستطيع إستخدام <code>call</code> لعمل تسلسل لمنشئات-constructors الكائن، وذلك على غرار جافا. في المثال التالي، تم تحديد منشئ الكائن <code>Product</code> مع اثنين من البارامترات <code>name</code> و <code>price</code>. والدالتات <code>Food</code> و <code>Toy</code> تستدعيان <code>Product</code> ممرر لها <code>this</code> و <code>name</code> و <code>price</code>. تقوم Product بتهيئة الخاصيتان <code>name</code> و <code>price</code> فيما تقوم كلا الدالتان المتخصصتان بتحديد ال <code>category</code>.</p> + +<pre class="brush: js notranslate">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); +</pre> + +<h3 dir="rtl" id="إستخدام_ال_call_لإستدعاء_الدالة_المجهولة_الاسم-anonymous_function">إستخدام ال call لإستدعاء الدالة المجهولة الاسم-anonymous function </h3> + +<p dir="rtl">في هذا المثال قمنا بانشاء الدالة المجهولة واستخدمنا <code>call</code> لإستدعاءها على كل كائن في المصفوفة. الغرض الرئيسي من الدالة المجهولة هو إضافة الدالة <code>print</code> الى كل كائن، والتي ستكون قادرة على طباعة الفهرس الصحيح لكائنات المصفوفة. تمرير كائن على شكل قيمة <code>this</code><span id="result_box" lang="ar"><span> </span></span><span lang="ar"><span>ليس ضروريًا، ولكن تم إنجازه لغرض توضيحي.</span></span></p> + +<pre class="brush: js notranslate">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); +} +</pre> + +<h3 dir="rtl" id="استخدام_call_لاستدعاء_دالة_وتحديد_السياق-context_ل_this">استخدام <code>call</code> لاستدعاء دالة وتحديد السياق-context ل <code>this</code></h3> + +<p dir="rtl">في المثال أدناه، عندما سنقوم باستدعاء <code>greet</code> سترتبط قيمة <code>this</code> بالكائن <code>obj.</code></p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 dir="rtl" id="إستخدام_الـcall_لاستدعاء_دالة_وبدون_تحديد_البرامتر_الاول">إستخدام الـ<code>call</code> لاستدعاء دالة وبدون تحديد البرامتر الاول</h3> + +<p dir="rtl">في المثال أدناه ،قمنا باستدعاء الدالة <code>display</code> من دون تمرير البرامتر الاول. إذا لم يتم تمرير قيمة <code>this</code> في البرامتر الاول فسترتبط بالكائن العام-global object.</p> +</div> + +<pre class="brush: js notranslate">var sData = 'Wisen'; + +function display(){ + console.log('sData value is %s ', this.sData); +} + +display.call(); // sData value is Wisen +</pre> + +<div class="blockIndicator note" dir="rtl"> +<p>تذكر ان قيمة <code>this</code> ستكون ب <code>undefined</code> في الوضع الصارم. انظر ادناه:</p> +</div> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="string token">'use strict'</span><span class="punctuation token">;</span> + +<span class="keyword token">var</span> sData <span class="operator token">=</span> <span class="string token">'Wisen'</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">display</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'sData value is %s '</span><span class="punctuation token">,</span> <span class="keyword token">this</span><span class="punctuation token">.</span>sData<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +display<span class="punctuation token">.</span><span class="function token">call</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Cannot read the property of 'sData' of undefined</span></code></pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Function.call")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li> + <p><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></p> + </li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Function</code> constructor</strong> creates a new <code>Function</code> 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.</p> + +<div>{{EmbedInteractiveExample("pages/js/function-constructor.html")}}</div> + + + +<p>Every JavaScript function is actually a <code>Function</code> object. This can be seen with the code <code>(function(){}).constructor === Function</code> which returns true.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code because such functions are parsed with the rest of the code.</p> + +<p>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.</p> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> 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 <code>new</code> with <code>Function</code>.</p> + +<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> + +<p>The global <code>Function</code> 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")}}.</p> + +<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Function_instances"><code>Function</code> instances</h2> + +<p><code>Function</code> 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 <code>Function</code> instances.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> + +<p>The following code creates a <code>Function</code> object that takes two arguments.</p> + +<pre class="brush: js">// 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 +</pre> + +<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> + +<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> + +<p>Functions created with the <code>Function</code> 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 <code>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> + +<pre class="brush: js">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 +</pre> + +<p>The "proper" way to execute external code with <code>Function</code> (for maximum minifyability).</p> + +<pre class="brush: js">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</pre> + +<p>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.</p> + +<pre class="brush: js">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)) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("AsyncFunction")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> 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 +--- +<div> + {{jsSidebar("Objects")}}</div> +<h2 id="Summary" name="Summary">Summary</h2> +<p>This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.</p> +<div class="onlyinclude"> + <p>The term "global objects" (or standard built-in objects) here is not to be confused with the <em>global object</em>. Here, global objects refer to <em>objects in the global scope</em> (but only if ECMAScript 5 strict mode is not used! Otherwise it returns <code>undefined</code>). The <em>global object</em> itself can be accessed by the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope <em>consists</em><em> of</em> the properties of the global object (including inherited properties, if any).</p> + <p>Other objects in the global scope are either <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">created by the user script</a> or provided by the host application. The host objects available in browser contexts are documented in the <a href="/en-US/docs/Web/API/Reference">API reference</a>. For more information about the distinction between the <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> and core <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + <h2 id="Standard_objects_(by_category)">Standard objects (by category)</h2> + <h3 id="Value_properties">Value properties</h3> + <p>Global properties returning a simple value.</p> + <ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> + </ul> + <h3 id="Function_properties">Function properties</h3> + <p>Global functions returning the result of a specific routine.</p> + <ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline()}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline()}}</li> + </ul> + <h3 id="Fundamental_objects">Fundamental objects</h3> + <p>General language objects, functions and errors.</p> + <ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} {{experimental_inline()}}</li> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError")}}</li> + <li>{{jsxref("InternalError")}}</li> + <li>{{jsxref("RangeError")}}</li> + <li>{{jsxref("ReferenceError")}}</li> + <li>{{jsxref("StopIteration")}}</li> + <li>{{jsxref("SyntaxError")}}</li> + <li>{{jsxref("TypeError")}}</li> + <li>{{jsxref("URIError")}}</li> + </ul> + <h3 id="Numbers_and_dates">Numbers and dates</h3> + <p>Objects dealing with numbers, dates and mathematical calculations.</p> + <ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> + </ul> + <h3 id="Text_processing">Text processing</h3> + <p>Objects for manipulating texts.</p> + <ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> + </ul> + <h3 id="Indexed_collections">Indexed collections</h3> + <p>Collections ordered by an index. Array-type objects.</p> + <ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline()}}</li> + </ul> + <h3 id="Keyed_collections">Keyed collections</h3> + <p>Collections of objects as keys. Elements iterable in insertion order.</p> + <ul> + <li>{{jsxref("Map")}} {{experimental_inline()}}</li> + <li>{{jsxref("Set")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakMap")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakSet")}} {{experimental_inline()}}</li> + </ul> + <h3 id="Structured_data">Structured data</h3> + <p>Data buffers and <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation.</p> + <ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> + </ul> + <h3 id="Control_abstraction_objects">Control abstraction objects</h3> + <ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Generator")}} {{experimental_inline()}}</li> + <li>{{jsxref("Promise")}} {{experimental_inline()}}</li> + </ul> + <h3 id="Reflection">Reflection</h3> + <ul> + <li>{{jsxref("Reflect")}} {{experimental_inline()}}</li> + <li>{{jsxref("Proxy")}} {{experimental_inline()}}</li> + </ul> + <h3 id="Internationalization">Internationalization</h3> + <p>Additions to the ECMAScript core for language-sensitive functionalities.</p> + <ul> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> + </ul> + <h3 id="Other">Other</h3> + <ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code></li> + </ul> +</div> +<p> </p> 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 +--- +<div>{{JSRef("Global_Objects", "JSON")}}</div> + +<h2 id="Summary" name="Summary">Summary</h2> +<p>The <strong><code>JSON</code></strong> object contains methods for parsing <a class="external" href="http://json.org/">JavaScript Object Notation</a> ({{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.</p> + +<h2 id="Description" name="Description">Description</h2> + +<h3 id="JavaScript_Object_Notation" name="JavaScript_Object_Notation">JavaScript Object Notation</h3> +<p>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 <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>.</p> +<table> + <caption>JavaScript and JSON differences</caption> + <thead> + <tr> + <th scope="col">JavaScript type</th> + <th scope="col">JSON differences</th> + </tr> + </thead> + <tbody> + <tr> + <td>Objects and Arrays</td> + <td>Property names must be double-quoted strings; trailing commas are forbidden.</td> + </tr> + <tr> + <td>Numbers</td> + <td>Leading zeros are prohibited; a decimal point must be followed by at least one digit.</td> + </tr> + <tr> + <td>Strings</td> + <td> + <p>Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (<a href="http://unicode-table.com/en/2028/">U+2028</a>) and paragraph separator (<a href="http://unicode-table.com/en/2029/">U+2029</a>) 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:</p> +<pre class="brush: js"> +var code = '"\u2028\u2029"'; +JSON.parse(code); // works fine +eval(code); // fails +</pre> + </td> + </tr> + </tbody> +</table> +<p>The full JSON syntax is as follows:</p> +<pre><var>JSON</var> = <strong>null</strong> + <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> + <em>or</em> <var>JSONNumber</var> + <em>or</em> <var>JSONString</var> + <em>or</em> <var>JSONObject</var> + <em>or</em> <var>JSONArray</var> + +<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> + <em>or</em> <var>PositiveNumber</var> +<var>PositiveNumber</var> = DecimalNumber + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> + <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> +<var>DecimalNumber</var> = <strong>0</strong> + <em>or</em> <var>OneToNine</var> <var>Digits</var> +<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> + <em>or</em> <strong>E</strong> <var>Exponent</var> +<var>Exponent</var> = <var>Digits</var> + <em>or</em> <strong>+</strong> <var>Digits</var> + <em>or</em> <strong>-</strong> <var>Digits</var> +<var>Digits</var> = <var>Digit</var> + <em>or</em> <var>Digits</var> <var>Digit</var> +<var>Digit</var> = <strong>0</strong> through <strong>9</strong> +<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> + +<var>JSONString</var> = <strong>""</strong> + <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> +<var>StringCharacters</var> = <var>StringCharacter</var> + <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> +<var>StringCharacter</var> = any character + <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F + <em>or</em> <var>EscapeSequence</var> +<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> + <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> +<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> + <em>or</em> <strong>A</strong> through <strong>F</strong> + <em>or</em> <strong>a</strong> through <strong>f</strong> + +<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> + <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> +<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> + <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> + +<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> + <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> +<var>ArrayElements</var> = <var>JSON</var> + <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> +</pre> +<p>Insignificant whitespace may be present anywhere except within a <code><var>JSONNumber</var></code> (numbers must contain no whitespace) or <code><var>JSONString</var></code> (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (<a href="http://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="http://unicode-table.com/en/0020/">U+0020</a>) characters are the only valid whitespace characters.</p> + +<h2 id="Methods" name="Methods">Methods</h2> +<dl> + <dt>{{jsxref("JSON.parse()")}}</dt> + <dd>Parse a string as JSON, optionally transform the produced value and its properties, and return the value.</dd> + <dt>{{jsxref("JSON.stringify()")}}</dt> + <dd>Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.</dd> +</dl> + +<h2 id="Polyfill" name="Polyfill">Polyfill</h2> +<p>The <code>JSON</code> 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 <code>JSON</code> object in implementations which do not natively support it (like Internet Explorer 6).</p> +<p>The following algorithm is an imitation of the native <code>JSON</code> object:</p> +<pre class="brush: js">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); + } + }; +} +</pre> +<p>More complex well-known <a class="external" href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfills</a> for the <code>JSON</code> object are <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> and <a class="external" href="http://bestiejs.github.com/json3">JSON3</a>.</p> + +<h2 id="Specifications" name="Specifications">Specifications</h2> +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> +<div>{{CompatibilityTable}}</div> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("8.0")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("4.0")}}</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p> + +<h2 id="See_also" name="See_also">See also</h2> +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON">Using native <code>JSON</code></a></li> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">The <strong><code>Map</code></strong> object holds key-value pairs and remembers the original insertion order of the keys.</span> Any value (both objects and {{glossary("Primitive", "primitive values")}}) may be used as either a key or a value.</p> + +<h2 id="Description">Description</h2> + +<p>A <code>Map</code> object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of <code>[<var>key</var>, <var>value</var>]</code> for each iteration.</p> + +<h3 id="Key_equality">Key equality</h3> + +<ul> + <li>Key equality is based on the <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality"><code>sameValueZero</code></a> algorithm.</li> + <li>{{jsxref("NaN")}} is considered the same as <code>NaN</code> (even though <code>NaN !== NaN</code>) and all other values are considered equal according to the semantics of the <code>===</code> operator.</li> + <li>In the current ECMAScript specification, <code>-0</code> and <code>+0</code> are considered equal, although this was not so in earlier drafts. See <em>"Value equality for -0 and 0"</em> in the <a href="#Browser_compatibility">Browser compatibility</a> table for details.</li> +</ul> + +<h3 id="Objects_vs._Maps">Objects vs. Maps</h3> + +<p>{{jsxref("Object")}} is similar to <code>Map</code>—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), <code>Object</code>s have been used as <code>Map</code>s historically.</p> + +<p>However, there are important differences that make <code>Map</code> preferable in certain cases:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row"></th> + <th scope="col">Map</th> + <th scope="col">Object</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">Accidental Keys</th> + <td>A <code>Map</code> does not contain any keys by default. It only contains what is explicitly put into it.</td> + <td> + <p>An <code>Object</code> has a prototype, so it contains default keys that could collide with your own keys if you're not careful.</p> + + <div class="blockIndicator note"> + <p><strong>Note:</strong> As of ES5, this can be bypassed by using {{jsxref("Object.create", "Object.create(null)")}}, but this is seldom done.</p> + </div> + </td> + </tr> + <tr> + <th scope="row">Key Types</th> + <td>A <code>Map</code>'s keys can be any value (including functions, objects, or any primitive).</td> + <td>The keys of an <code>Object</code> must be either a {{jsxref("String")}} or a {{jsxref("Symbol")}}.</td> + </tr> + <tr> + <th scope="row">Key Order</th> + <td> + <p>The keys in <code>Map</code> are ordered. Thus, when iterating over it, a <code>Map</code> object returns keys in order of insertion.</p> + </td> + <td> + <p>The keys of an <code>Object</code> are not ordered.</p> + + <div class="blockIndicator note"> + <p><strong>Note:</strong> Since ECMAScript 2015, objects <em>do</em> preserve creation order for string and <code>Symbol</code> 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.</p> + </div> + </td> + </tr> + <tr> + <th scope="row">Size</th> + <td>The number of items in a <code>Map</code> is easily retrieved from its {{jsxref("Map.prototype.size", "size")}} property.</td> + <td>The number of items in an <code>Object</code> must be determined manually.</td> + </tr> + <tr> + <th scope="row">Iteration</th> + <td>A <code>Map</code> is an <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a>, so it can be directly iterated.</td> + <td>Iterating over an <code>Object</code> requires obtaining its keys in some fashion and iterating over them.</td> + </tr> + <tr> + <th scope="row">Performance</th> + <td> + <p>Performs better in scenarios involving frequent additions and removals of key-value pairs.</p> + </td> + <td> + <p>Not optimized for frequent additions and removals of key-value pairs.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Setting_object_properties">Setting object properties</h3> + +<p>Setting Object properties works for Map objects as well, and can cause considerable confusion.</p> + +<p>Therefore, this appears to work in a way:</p> + +<pre class="syntaxbox example-bad brush js notranslate">let wrongMap = new Map() +wrongMap['bla'] = 'blaa' +wrongMap['bla2'] = 'blaaa2' + +console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } +</pre> + +<p>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:</p> + +<pre class="syntaxbox example-bad brush js notranslate">wrongMap.has('bla') // false +wrongMap.delete('bla') // false +console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' }</pre> + +<p>The correct usage for storing data in the Map is through the set(key, value) method.</p> + +<pre class="syntaxbox brush js example-good notranslate">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 + +</pre> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{jsxref("Map/Map", "Map()")}}</dt> + <dd>Creates a new <code>Map</code> object.</dd> +</dl> + +<h2 id="Static_properties">Static properties</h2> + +<dl> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> +</dl> + +<h2 id="Instance_properties">Instance properties</h2> + +<dl> + <dt>{{jsxref("Map.prototype.size")}}</dt> + <dd>Returns the number of key/value pairs in the <code>Map</code> object.</dd> +</dl> + +<h2 id="Instance_methods">Instance methods</h2> + +<dl> + <dt>{{jsxref("Map.prototype.clear()")}}</dt> + <dd>Removes all key-value pairs from the <code>Map</code> object.</dd> + <dt>{{jsxref("Map.delete", "Map.prototype.delete(<var>key</var>)")}}</dt> + <dd>Returns <code>true</code> if an element in the <code>Map</code> object existed and has been removed, or <code>false</code> if the element does not exist. <code>Map.prototype.has(<var>key</var>)</code> will return <code>false</code> afterwards.</dd> + <dt>{{jsxref("Map.prototype.entries()")}}</dt> + <dd>Returns a new <code>Iterator</code> object that contains <strong>an array of <code>[<var>key</var>, <var>value</var>]</code></strong> for each element in the <code>Map</code> object in insertion order.</dd> + <dt>{{jsxref("Map.forEach", "Map.prototype.forEach(<var>callbackFn</var>[, <var>thisArg</var>])")}}</dt> + <dd>Calls <code><var>callbackFn</var></code> once for each key-value pair present in the <code>Map</code> object, in insertion order. If a <code><var>thisArg</var></code> parameter is provided to <code>forEach</code>, it will be used as the <code>this</code> value for each callback.</dd> + <dt>{{jsxref("Map.get", "Map.prototype.get(<var>key</var>)")}}</dt> + <dd>Returns the value associated to the <code><var>key</var></code>, or <code>undefined</code> if there is none.</dd> + <dt>{{jsxref("Map.has", "Map.prototype.has(<var>key</var>)")}}</dt> + <dd>Returns a boolean asserting whether a value has been associated to the <code><var>key</var></code> in the <code>Map</code> object or not.</dd> + <dt>{{jsxref("Map.prototype.keys()")}}</dt> + <dd>Returns a new <code>Iterator</code> object that contains the <strong>keys</strong> for each element in the <code>Map</code> object in insertion order.</dd> + <dt>{{jsxref("Map.set", "Map.prototype.set(<var>key</var>, <var>value</var>)")}}</dt> + <dd>Sets the <code><var>value</var></code> for the <code><var>key</var></code> in the <code>Map</code> object. Returns the <code>Map</code> object.</dd> + <dt>{{jsxref("Map.prototype.values()")}}</dt> + <dd>Returns a new <code>Iterator</code> object that contains the <strong>values</strong> for each element in the <code>Map</code> object in insertion order.</dd> + <dt>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</dt> + <dd>Returns a new <code>Iterator</code> object that contains <strong>an array of <code>[<var>key</var>, <var>value</var>]</code></strong> for each element in the <code>Map</code> object in insertion order.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_the_Map_object">Using the <code>Map</code> object</h3> + +<pre class="brush: js notranslate">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 () {} +</pre> + +<h3 id="Using_NaN_as_Map_keys">Using <code>NaN</code> as <code>Map</code> keys</h3> + +<p>{{jsxref("NaN")}} can also be used as a key. Even though every <code>NaN</code> is not equal to itself (<code>NaN !== NaN</code> is true), the following example works because <code>NaN</code>s are indistinguishable from each other:</p> + +<pre class="brush: js notranslate">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" +</pre> + +<h3 id="Iterating_Map_with_for..of">Iterating <code>Map</code> with <code>for..of</code></h3> + +<p>Maps can be iterated using a <code>for..of</code> loop:</p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 id="Iterating_Map_with_forEach">Iterating <code>Map</code> with <code>forEach()</code></h3> + +<p>Maps can be iterated using the {{jsxref("Map.prototype.forEach", "forEach()")}} method:</p> + +<pre class="brush: js notranslate">myMap.forEach(function(value, key) { + console.log(key + ' = ' + value) +}) +// 0 = zero +// 1 = one +</pre> + +<h3 id="Relation_with_Array_objects">Relation with Array objects</h3> + +<pre class="brush: js notranslate">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"] +</pre> + +<h3 id="Cloning_and_merging_Maps">Cloning and merging <code>Map</code>s</h3> + +<p>Just like <code>Array</code>s, <code>Map</code>s can be cloned:</p> + +<pre class="brush: js notranslate">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)</pre> + +<div class="blockIndicator note"> +<p><strong>Important:</strong> Keep in mind that <em>the data itself</em> is not cloned.</p> +</div> + +<p>Maps can be merged, maintaining key uniqueness:</p> + +<pre class="brush: js notranslate">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</pre> + +<p>Maps can be merged with Arrays, too:</p> + +<pre class="brush: js notranslate">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</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.</p> + +<h2 id="Description">Description</h2> + +<p>Unlike the other global objects, <code>Math</code> is not a constructor. All properties and methods of <code>Math</code> are static. You refer to the constant pi as <code>Math.PI</code> and you call the sine function as <code>Math.sin(x)</code>, where <code>x</code> is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>Euler's constant and the base of natural logarithms, approximately 2.718.</dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd>Natural logarithm of 2, approximately 0.693.</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>Natural logarithm of 10, approximately 2.303.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>Base 2 logarithm of E, approximately 1.443.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>Base 10 logarithm of E, approximately 0.434.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>Ratio of the circumference of a circle to its diameter, approximately 3.14159.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>Square root of 2, approximately 1.414.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<div class="note"> +<p>Note that the trigonometric functions (<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>) expect or return angles in radians. To convert radians to degrees, divide by <code>(Math.PI / 180)</code>, and multiply by this to convert the other way.</p> +</div> + +<div class="note"> +<p>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.</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>Returns the absolute value of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>Returns the arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> + <dd>Returns the hyperbolic arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>Returns the arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>Returns the arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> + <dd>Returns the hyperbolic arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> + <dd>Returns the cube root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>Returns the smallest integer greater than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> + <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>Returns the cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> + <dd>Returns the hyperbolic cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>Returns E<sup>x</sup>, where <var>x</var> is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> + <dd>Returns subtracting 1 from <code>exp(x)</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>Returns the largest integer less than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> + <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> + <dd>Returns the square root of the sum of squares of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> + <dd>Returns the result of a 32-bit integer multiplication.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of <code>1 + x</code> for a number x.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> + <dd>Returns the base 10 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> + <dd>Returns the base 2 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>Returns the largest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>Returns the smallest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>Returns base to the exponent power, that is, <code>base<sup>exponent</sup></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>Returns a pseudo-random number between 0 and 1.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>Returns the value of a number rounded to the nearest integer.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> + <dd>Returns the sign of the x, indicating whether x is positive, negative or zero.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>Returns the sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> + <dd>Returns the hyperbolic sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>Returns the positive square root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>Returns the tangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> + <dd>Returns the hyperbolic tangent of a number.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>Returns the string <code>"Math"</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> + <dd>Returns the integer part of the number x, removing any fractional digits.</dd> +</dl> + +<h2 id="Extending_the_Math_object">Extending the <code>Math</code> object</h2> + +<p>As with most of the built-in objects in JavaScript, the <code>Math</code> object can be extended with custom properties and methods. To extend the <code>Math</code> object, you do not use <code>prototype</code>. Instead, you directly extend <code>Math</code>:</p> + +<pre>Math.propName = propValue; +Math.methodName = methodRef;</pre> + +<p>For instance, the following example adds a method to the <code>Math</code> object for calculating the <em>greatest common divisor</em> of a list of arguments.</p> + +<pre class="brush: js">/* 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; + } +};</pre> + +<p>Try it:</p> + +<pre class="brush: js">console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>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.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> 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 +--- +<div dir="rtl">{{JSRef}}</div> + +<p dir="rtl">بالرجوع إلى {{jsxref("Object")}}constructor ووظيفتها إنشاء حالات من الاوبجكت (الكائن) .نذكرك بأن قيمة الخصائص التي تشير إليها تلك الفانكشان تشير لنفسها ولا تشير إلى سلسة تحتوي على إسم الفانكشان القيمة تقرأ فقط قيم بدائية مثل <code>1</code>, <code>true</code> و <code>"test"</code>.</p> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">جميع الاوبجكت ( مع بعض الاستثائات نشأت مع <code>Object.create(null)</code> ) وستملك وقتها جميعا خاصية الـ <code>constructor </code>. اما الكائنات المنشأة بدون إستخدام الكونستراكتور بشكل صريح ( مثل object & array literals ) ستملك أيضا خصائص الكونستركتور بشكل أساسي</p> + +<pre class="brush: js">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 +</pre> + +<h2 dir="rtl" id="أمثلة">أمثلة</h2> + +<h3 dir="rtl" id="عرض_الكونستركتور_للأوبجكت">عرض الكونستركتور للأوبجكت</h3> + +<p dir="rtl">في المثال التالي قمنا بإنشاء بروتوتيب <code>Tree </code>و اوبجكت بإسم <code>theTree</code> المثال هنا يعرض خصائص الـ<code>constructor</code> للكائن <code>theTree</code></p> + +<pre class="brush: js" dir="rtl">function Tree(name) { + this.name = name; +} + +var theTree = new Tree('Redwood'); +console.log('theTree.constructor is ' + theTree.constructor); +</pre> + +<p dir="rtl">عندما تقوم بكتابة الكود بعالية ستحصل على النتيجة الاتية ليوضح لك أكثر :-</p> + +<pre class="brush: js">theTree.constructor is function Tree(name) { + this.name = name; +} +</pre> + +<h3 dir="rtl" id="تغير_الكونستركتور_الخاص_بالاوبجكت">تغير الكونستركتور الخاص بالاوبجكت</h3> + +<p>The following example shows how to modify constructor value of generic objects. Only <code>true</code>, <code>1</code> and <code>"test"</code> will not be affected as they have read-only native constructors. This example shows that it is not always safe to rely on the <code>constructor</code> property of an object.</p> + +<pre class="brush:js">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')); +</pre> + +<p>This example displays the following output:</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.1', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="دعم_المتصفحات">دعم المتصفحات</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.constructor")}}</p> +</div> 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 +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>Object</strong></code> constructor creates an object wrapper.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>Any value.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>The <code>Object</code> 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.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Properties_of_the_Object_constructor">Properties of the <code>Object</code> constructor</h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Has a value of 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Allows the addition of properties to all objects of type Object.</dd> +</dl> + +<h2 id="Methods_of_the_Object_constructor">Methods of the <code>Object</code> constructor</h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>Copies the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.entries()")}}</dt> + <dd>Returns an array containing all of the <code>[key, value]</code> pairs of a given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptors()")}}</dt> + <dd>Returns an object containing all own property descriptors for an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property).</dd> + <dt>{{jsxref("Object.values()")}}</dt> + <dd>Returns an array containing the values that correspond to all of a given object's <strong>own</strong> enumerable string properties.</dd> +</dl> + +<h2 id="Object_instances_and_Object_prototype_object"><code>Object</code> instances and <code>Object</code> prototype object</h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}</div> + +<h2 id="Deleting_a_property_from_an_object">Deleting a property from an object</h2> + +<p>There isn't any method in an Object itself to delete its own properties (e.g. like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete">Map.prototype.delete()</a></code>). To do so one has to use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete operator</a>.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</code>:</p> + +<pre class="brush: js">var o = new Object(); +</pre> + +<pre class="brush: js">var o = new Object(undefined); +</pre> + +<pre class="brush: js">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>String</code></strong> global object is a constructor for strings, or a sequence of characters.</p> + +<h2 id="Syntax">Syntax</h2> + +<p>String literals take the forms:</p> + +<pre class="syntaxbox">'string text' +"string text" +"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>Strings can also be created using the <code>String</code> global object directly:</p> + +<pre class="syntaxbox">String(thing)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Anything to be converted to a string.</dd> +</dl> + +<h3 id="Template_literals">Template literals</h3> + +<p>Starting with ECMAScript 2015, string literals can also be so-called <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a>:</p> + +<pre class="syntaxbox">`hello world` +`hello! + world!` +`hello ${who}` +escape `<a>${who}</a>`</pre> + +<dl> +</dl> + +<h3 id="Escape_notation">Escape notation</h3> + +<p>Beside regular, printable characters, special characters can be encoded using escape notation:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Code</th> + <th scope="col">Output</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>the NULL character</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>backslash</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>new line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>carriage return</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>vertical tab</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>tab</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>form feed</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>unicode codepoint</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>unicode codepoint {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>the Latin-1 character</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>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.</p> +</div> + +<dl> +</dl> + +<h3 id="Long_literal_strings">Long literal strings</h3> + +<p>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.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>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:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Description">Description</h2> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, 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.</p> + +<h3 id="Character_access">Character access</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>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:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>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.)</p> + +<h3 id="Comparing_strings">Comparing strings</h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> + +<pre class="brush: js">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.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinction_between_string_primitives_and_String_objects">Distinction between string primitives and <code>String</code> objects</h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> + +<pre class="brush: js">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" +</pre> + +<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> + +<pre class="brush: js">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" +</pre> + +<p>For these reasons, code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Note:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="String_generic_methods"><code>String</code> generic methods</h2> + +<div class="warning"> +<p><strong>String generics are non-standard, deprecated and will get removed near future</strong>.</p> +</div> + +<p>The <code>String</code> instance methods are also available in Firefox as of JavaScript 1.6 (<strong>not</strong> part of the ECMAScript standard) on the <code>String</code> object for applying <code>String</code> methods to any object:</p> + +<pre class="brush: js">var num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p>For migrating away from String generics, see also <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_string_generics">Warning: String.x is deprecated; use String.prototype.x instead</a>.</p> + +<p>{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.</p> + +<h2 id="String_instances"><code>String</code> instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="String_conversion">String conversion</h3> + +<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying <code>toString()</code>. It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:</p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.String")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p dir="rtl"><span class="seoSummary"><strong><code>startsWith()</code></strong></span><br> + <span class="seoSummary">.طريقة يمكنك<strong> تحقق</strong> بها<strong> إن كان </strong><code>نص</code> <strong>يبدء بالعبارة ما</strong> و تعيد لك<code> صحيح </code>أو <code>خطأ</code> </span></p> + +<div>{{EmbedInteractiveExample("pages/js/string-startswith.html")}}</div> + + + +<h2 dir="rtl" id="تركيب_الجملة_Syntax">تركيب الجملة | Syntax</h2> + +<pre class="syntaxbox"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> + +<h3 dir="rtl" id="المعاملات_Parameters">المعاملات | Parameters</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd dir="rtl">العبارة<strong> المبحوث عنها</strong> في<strong><code>النص.</code></strong></dd> + <dt><code>position </code>{{optional_inline}}</dt> + <dd dir="rtl">مكان الذي<strong> يبدأ البحث منه </strong>في<code><strong>النص </strong></code> <strong>الإفتراضي 0</strong></dd> +</dl> + +<h3 dir="rtl" id="القيمة_العائدة_Return_value">القيمة العائدة | Return value</h3> + +<p dir="rtl"><strong>العائد</strong> يكون<strong> صحيح</strong> إذا وجد <strong>تطابق</strong><br> + و إن <strong>لم يجيد تطابق</strong> يعيد لك <strong>خطأ</strong></p> + +<h2 dir="rtl" id="الوصف_Description">الوصف | Description</h2> + +<p dir="rtl"><strong><code>هذه الطريقة حساسة إتجاه الحروف<br> + case-sensitive</code></strong></p> + +<h2 dir="rtl" id="أمثلة_Examples">أمثلة | Examples</h2> + +<h3 id="Using_startsWith()">Using <code>startsWith()</code></h3> + +<pre class="brush: js">//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 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill <code>String.prototype.startsWith()</code> with the following snippet:</p> + +<pre class="brush: js">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; + } + }); +} +</pre> + +<p>A more robust (fully ES2015 specification compliant), but less performant and compact, Polyfill is available <a href="https://github.com/mathiasbynens/String.prototype.startsWith">on GitHub by Mathias Bynens</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="توافق_مع_متصفحات">توافق مع متصفحات</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.startsWith")}}</p> + +<h2 dir="rtl" id="ذات_صلة">ذات صلة</h2> + +<ul> + <li>{{jsxref("String.prototype.endsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> 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..cb667fd3d8 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/الارقام/index.html @@ -0,0 +1,12 @@ +--- +title: الارقام في الجافا سكربت +slug: Web/JavaScript/Reference/Global_Objects/الارقام +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<p> وهو كائن غلاف يستخدم لتمثيل ومعالجة الأرقام مثل <code>37</code><em> </em><strong>او </strong><code>9.25</code> <strong><code>Number</code></strong>منشئ يحتوي على الثوابت وطرق للعمل مع الأرقام. يمكن تحويل قيم الأنواع الأخرى إلى أرقام باستخدام <strong> </strong><strong><code>Number()</code>الوظيفة</strong>.</p> + +<p>جافا سكريبت <strong>رقم </strong>نوع عبارة عن قيمة <a class="external" href="https://en.wikipedia.org/wiki/Floating-point_arithmetic" rel="noopener">مزدوجة الدقة بتنسيق IEEE 754 تنسيق ثنائي 64 بت </a>ذات ، كما هو الحال <code>double</code>في <strong>Java</strong> أو <strong>C #</strong>. هذا يعني أنه يمكن أن يمثل قيمًا كسرية ، ولكن هناك بعض الحدود لما يمكن تخزينه. يحتفظ فقط بحوالي 17 رقم منزلاً عشريًا من الدقة ؛ الحساب يخضع <a class="external" href="https://en.wikipedia.org/wiki/Floating-point_arithmetic#Representable_numbers,_conversion_and_rounding" rel="noopener">للتقريب </a>. أكبر قيمة يمكن أن يحملها رقم هي حوالي <code><strong>1.8 × 10 <sup>308 </sup></strong></code>. يتم استبدال الأعداد التي تتجاوز ذلك بثابت الرقم الخاص <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>.</p> + +<p>الرقم الحرفي مثل <code>37</code>كود JavaScript هو قيمة فاصلة عائمة ، وليس عددًا صحيحًا. لا يوجد نوع عدد صحيح منفصل في الاستخدام اليومي الشائع. (يحتوي JavaScript الآن على <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt"><code>BigInt</code></a>نوع ، لكنه لم يتم تصميمه ليحل محل Number للاستخدامات اليومية. <code>37</code>لا يزال رقمًا ، وليس BigInt.)</p> + +<p>يمكن أيضًا التعبير عن الرقم بأشكال حرفية مثل <code>0b101</code>، <code>0o13</code>، <code>0x0A</code>. تعرف على المزيد حول العددي <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">قواعد المعجم هنا </a>.</p> 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 +--- +<div>{{JsSidebar}}</div> + +<p>This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more <a href="/en-US/docs/Web/JavaScript/Reference/About">about this reference</a>.</p> + +<h2 id="Global_Objects">Global Objects</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">JavaScript standard built-in objects</a>, along with their methods and properties.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}</div> + +<h2 id="Statements">Statements</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements and declarations</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}</div> + +<h2 id="Expressions_and_operators">Expressions and operators</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Operators">JavaScript expressions and operators</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}</div> + +<h2 id="Functions">Functions</h2> + +<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">JavaScript functions</a> to develop your applications.</p> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments"><code>arguments</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/arrow_functions">Arrow functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/default_parameters">Default parameters</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> + +<h2 id="Additional_reference_pages">Additional reference pages</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> +</ul> 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 +--- +<div>{{jsSidebar("Operators")}}</div> + +<div dir="rtl"><strong>الإسناد بالتفكيك</strong> هو تعبير جافاسكربت يجعل من الممكن فك القيم من المصفوفات ( Arrays ) أو الخصائص من الكائنات ( Objects ) إلى متغيرات مميزة.</div> + +<div dir="rtl"></div> + +<div>{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html", "taller")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="brush:js">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} +</pre> + +<h2 dir="rtl" id="التفاصيل">التفاصيل</h2> + +<p dir="rtl">توفر تعبيرات الكائن (Object) والمصفوفة (Array) طريقة سهلة لإنشاء حزم بيانات مخصصة.</p> + +<pre class="brush: js">const x = [1, 2, 3, 4, 5]; +</pre> + +<p dir="rtl" id="tw-target-text">يَستخدِم<strong> الإسناد بالتفكيك (destructuring assignment)</strong> بنية مماثلة، ولكن على الجانب الأيسر من المهمة لتحديد القيم التي يجب فكها من مصدر المتغير الأساسي.</p> + +<pre dir="rtl" id="tw-target-text">const x = [1, 2, 3, 4, 5]; +const [y, z] = x; +console.log(y); // 1 +console.log(z); // 2 +</pre> + +<p dir="rtl">تشبه هذه الإمكانية الميزات الموجودة بلغات مثل Perl و Python.</p> + +<p dir="rtl"></p> + +<h2 dir="rtl" id="تفكيك_المصفوفات">تفكيك المصفوفات</h2> + +<h3 dir="rtl" id="تعيين_المتغير_الأساسي">تعيين المتغير الأساسي</h3> + +<pre class="brush: js">const foo = ['one', 'two', 'three']; + +const [red, yellow, green] = foo; +console.log(red); // "one" +console.log(yellow); // "two" +console.log(green); // "three" +</pre> + +<h3 id="Assignment_separate_from_declaration">Assignment separate from declaration</h3> + +<p>A variable can be assigned its value via destructuring separate from the variable's declaration.</p> + +<pre class="brush:js">let a, b; + +[a, b] = [1, 2]; +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h3 id="Default_values">Default values</h3> + +<p>A variable can be assigned a default, in the case that the value unpacked from the array is <code>undefined</code>.</p> + +<pre class="brush: js">let a, b; + +[a=5, b=7] = [1]; +console.log(a); // 1 +console.log(b); // 7 +</pre> + +<h3 id="Swapping_variables">Swapping variables</h3> + +<p>Two variables values can be swapped in one destructuring expression.</p> + +<p>Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the <a class="external" href="https://en.wikipedia.org/wiki/XOR_swap_algorithm">XOR-swap trick</a>).</p> + +<pre class="brush:js">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] + +</pre> + +<h3 id="Parsing_an_array_returned_from_a_function">Parsing an array returned from a function</h3> + +<p>It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.</p> + +<p>In this example, <code>f()</code> returns the values <code>[1, 2]</code> as its output, which can be parsed in a single line with destructuring.</p> + +<pre class="brush:js">function f() { + return [1, 2]; +} + +let a, b; +[a, b] = f(); +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h3 id="Ignoring_some_returned_values">Ignoring some returned values</h3> + +<p>You can ignore return values that you're not interested in:</p> + +<pre class="brush:js">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 +</pre> + +<p>You can also ignore all returned values:</p> + +<pre class="brush:js">[,,] = f(); +</pre> + +<h3 id="Assigning_the_rest_of_an_array_to_a_variable">Assigning the rest of an array to a variable</h3> + +<p>When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:</p> + +<pre class="brush: js">const [a, ...b] = [1, 2, 3]; +console.log(a); // 1 +console.log(b); // [2, 3]</pre> + +<p>Be aware that a {{jsxref("SyntaxError")}} will be thrown if a trailing comma is used on the left-hand side with a rest element:</p> + +<pre class="brush: js example-bad">const [a, ...b,] = [1, 2, 3]; + +// SyntaxError: rest element may not have a trailing comma +// Always consider using rest operator as the last element +</pre> + +<h3 id="Unpacking_values_from_a_regular_expression_match">Unpacking values from a regular expression match</h3> + +<p>When the regular expression <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec"> exec()</a></code> 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.</p> + +<pre class="brush:js">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" +</pre> + +<h2 id="Object_destructuring">Object destructuring</h2> + +<h3 id="Basic_assignment">Basic assignment</h3> + +<pre class="brush: js">const user = { + id: 42, + is_verified: true +}; + +const {id, is_verified} = user; + +console.log(id); // 42 +console.log(is_verified); // true +</pre> + +<h3 id="Assignment_without_declaration">Assignment without declaration</h3> + +<p>A variable can be assigned its value with destructuring separate from its declaration.</p> + +<pre class="brush:js">let a, b; + +({a, b} = {a: 1, b: 2});</pre> + +<div class="note"> +<p><strong>Notes</strong>: The parentheses <code>( ... )</code> around the assignment statement are required when using object literal destructuring assignment without a declaration.</p> + +<p><code>{a, b} = {a: 1, b: 2}</code> is not valid stand-alone syntax, as the <code>{a, b}</code> on the left-hand side is considered a block and not an object literal.</p> + +<p>However, <code>({a, b} = {a: 1, b: 2})</code> is valid, as is <code>const {a, b} = {a: 1, b: 2}</code></p> + +<p>Your <code>( ... )</code> expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.</p> +</div> + +<h3 id="Assigning_to_new_variable_names">Assigning to new variable names</h3> + +<p>A property can be unpacked from an object and assigned to a variable with a different name than the object property.</p> + +<pre class="brush: js">const o = {p: 42, q: true}; +const {p: foo, q: bar} = o; + +console.log(foo); // 42 +console.log(bar); // true</pre> + +<p>Here, for example, <code>const {p: foo} = o</code> takes from the object <code>o</code> the property named <code>p</code> and assigns it to a local variable named <code>foo</code>.</p> + +<h3 id="Default_values_2">Default values</h3> + +<p>A variable can be assigned a default, in the case that the value unpacked from the object is <code>undefined</code>.</p> + +<pre class="brush: js">const {a = 10, b = 5} = {a: 3}; + +console.log(a); // 3 +console.log(b); // 5</pre> + +<h3 id="Assigning_to_new_variables_names_and_providing_default_values">Assigning to new variables names and providing default values</h3> + +<p>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 <code>undefined</code>.</p> + +<pre class="brush: js">const {a: aa = 10, b: bb = 5} = {a: 3}; + +console.log(aa); // 3 +console.log(bb); // 5 +</pre> + +<h3 id="Unpacking_fields_from_objects_passed_as_function_parameter">Unpacking fields from objects passed as function parameter</h3> + +<pre class="brush:js">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"</pre> + +<p>This unpacks the <code>id</code>, <code>displayName</code> and <code>firstName</code> from the user object and prints them.</p> + +<h3 id="Setting_a_function_parameters_default_value">Setting a function parameter's default value</h3> + +<pre class="brush: js">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 +});</pre> + +<div class="note"> +<p>In the function signature for <strong><code>drawChart</code></strong> above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: <code>{size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}</code>. 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 <code><strong>drawChart()</strong></code> 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.</p> +</div> + +<h3 id="Nested_object_and_array_destructuring">Nested object and array destructuring</h3> + +<pre class="brush:js">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"</pre> + +<h3 id="For_of_iteration_and_destructuring">For of iteration and destructuring</h3> + +<pre class="brush: js">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" +</pre> + +<h3 id="Computed_object_property_names_and_destructuring">Computed object property names and destructuring</h3> + +<p>Computed property names, like on <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">object literals</a>, can be used with destructuring.</p> + +<pre class="brush: js">let key = 'z'; +let {[key]: foo} = {z: 'bar'}; + +console.log(foo); // "bar" +</pre> + +<h3 id="Rest_in_Object_Destructuring">Rest in Object Destructuring</h3> + +<p>The <a class="external external-icon" href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> proposal (stage 4) adds the <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a> syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.</p> + +<pre class="brush: js">let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} +a; // 10 +b; // 20 +rest; // { c: 30, d: 40 }</pre> + +<h3 id="Invalid_JavaScript_identifier_as_a_property_name">Invalid JavaScript identifier as a property name</h3> + +<p>Destructuring can be used with property names that are not valid JavaScript {{glossary("Identifier", "identifiers")}} by providing an alternative identifier that is valid.</p> + +<pre class="brush: js">const foo = { 'fizz-buzz': true }; +const { 'fizz-buzz': fizzBuzz } = foo; + +console.log(fizzBuzz); // "true" +</pre> + +<h3 id="Combined_Array_and_Object_Destructuring">Combined Array and Object Destructuring</h3> + +<p>Array and Object destructuring can be combined. Say you want the third element in the array <code>props</code> below, and then you want the <code>name</code> property in the object, you can do the following:</p> + +<pre class="brush: js">const props = [ + { id: 1, name: 'Fizz'}, + { id: 2, name: 'Buzz'}, + { id: 3, name: 'FizzBuzz'} +]; + +const [,, { name }] = props; + +console.log(name); // "FizzBuzz" +</pre> + +<h3 id="The_prototype_chain_is_looked_up_when_the_object_is_deconstructed">The prototype chain is looked up when the object is deconstructed </h3> + +<p>When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.</p> + +<pre class="brush: js">let obj = {self: '123'}; +obj.__proto__.prot = '456'; +const {self, prot} = obj; +// self "123" +// prot "456"(Access to the prototype chain)</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.operators.destructuring")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment operators</a></li> + <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">"ES6 in Depth: Destructuring" on hacks.mozilla.org</a></li> +</ul> 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 +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>This chapter documents all the JavaScript language operators, expressions and keywords.</p> + +<h2 id="Expressions_and_operators_by_category">Expressions and operators by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Primary_expressions">Primary expressions</h3> + +<p>Basic keywords and general expressions in JavaScript.</p> + +<dl> + <dt>{{jsxref("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to the function's execution context.</dd> + <dt>{{jsxref("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{jsxref("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{jsxref("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{jsxref("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function.</dd> + <dt>{{jsxref("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}</dt> + <dd>The <code>async function</code> defines an async function expression.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/await", "await")}}</dt> + <dd>Pause and resume an async function and wait for the promise's resolution/rejection.</dd> + <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Left-hand-side_expressions">Left-hand-side expressions</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> + <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> + <dt>{{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{jsxref("Operators/Spread_operator", "...obj")}}</dt> + <dd>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.</dd> +</dl> + +<h3 id="Increment_and_decrement">Increment and decrement</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Unary_operators">Unary operators</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> + <dd>Exponentiation operator.</dd> +</dl> + +<h3 id="Relational_operators">Relational operators</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<div class="note"> +<p><strong>Note: =></strong> is not an operator, but the notation for <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>.</p> +</div> + +<h3 id="Equality_operators">Equality operators</h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Binary_logical_operators">Binary logical operators</h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Conditional_(ternary)_operator">Conditional (ternary) operator</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>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.</p> + </dd> +</dl> + +<h3 id="Comma_operator">Comma operator</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Non-standard_features">Non-standard features</h3> + +<dl> + <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> + <dd>The <code>function</code> 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.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> + <dd>Generator comprehensions.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread operator, destructuring assignment, <code>super</code> keyword.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> +</ul> 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 +--- +<div><font><font>9 9090 jsSidebar ("عوامل التشغيل")}}</font></font></div> + +<p><span class="seoSummary"><font><font>في </font></font><strong><code>new</code><font><font>المشغل</font></font></strong><font><font> يتيح للمطورين إنشاء مثيل من نوع الكائن المعرفة من قبل المستخدم أو واحد من أنواع الكائنات المضمنة التي لديه وظيفة المنشئ.</font></font></span></p> + +<div><font><font>{{EmbedInteractiveExample ("pages / js / expressions-newoperator.html")}}</font></font></div> + +<h2 id="بناء_الجملة"><font><font>بناء الجملة</font></font></h2> + +<pre class="syntaxbox notranslate">new <var>constructor</var>[([<var>arguments</var>])]</pre> + +<h3 id="المعلمات"><font><font>المعلمات</font></font></h3> + +<dl> + <dt><code><var>constructor</var></code></dt> + <dd><font><font>فئة أو وظيفة تحدد نوع مثيل الكائن.</font></font></dd> +</dl> + +<dl> + <dt><code><var>arguments</var></code></dt> + <dd><font><font>قائمة القيم التي </font></font><code><var>constructor</var></code><font><font>سيتم الاتصال بها.</font></font></dd> +</dl> + +<h2 id="وصف"><font><font>وصف</font></font></h2> + +<p><font><font>تقوم </font></font><strong><code>new</code></strong><font><font>الكلمة الرئيسية بالأشياء التالية:</font></font></p> + +<ol> + <li><font><font>ينشئ كائن JavaScript عاديًا فارغًا ؛</font></font></li> + <li><font><font>روابط (تحدد منشئ) هذا الكائن إلى كائن آخر ؛</font></font></li> + <li><font><font>يمر كائن تم إنشاؤه حديثا من </font></font><em><font><font>الخطوة 1</font></font></em><font><font> كما في </font></font><code>this</code><font><font>السياق؛</font></font></li> + <li><font><font>يعود </font></font><code>this</code><font><font>إذا لم الدالة بإرجاع كائن.</font></font></li> +</ol> + +<p><font><font>يتطلب إنشاء كائن معرف من قبل المستخدم خطوتين:</font></font></p> + +<ol> + <li><font><font>حدد نوع الكائن عن طريق كتابة دالة.</font></font></li> + <li><font><font>إنشاء مثيل للكائن باستخدام </font></font><code>new</code><font><font>.</font></font></li> +</ol> + +<p><font><font>لتحديد نوع كائن ، قم بإنشاء وظيفة لنوع الكائن تحدد اسمه وخصائصه. </font><font>يمكن أن يكون للكائن خاصية تكون في حد ذاتها كائنًا آخر. </font><font>انظر الأمثلة أدناه.</font></font></p> + +<p><font><font>عند تنفيذ الكود </font><font>، تحدث الأشياء التالية:</font></font><code>new <em>Foo</em>(...)</code></p> + +<ol> + <li><font><font>يتم إنشاء كائن جديد ، وراثة من </font></font><code><em>Foo</em>.prototype</code><font><font>.</font></font></li> + <li><code><em>Foo</em></code><font><font>يتم استدعاء </font><font>دالة المُنشئ بالوسيطات </font><font>المحددة ، وتكون </font></font><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code><font><font>مرتبطة بالكائن الذي تم إنشاؤه حديثًا. </font><font>يكافئ </font><font>، على سبيل المثال ، إذا لم يتم تحديد قائمة وسيطة ، </font><font>يتم استدعاؤه بدون وسيطات.</font></font><code>new <em>Foo</em></code><code>new <em>Foo</em>()</code><code><em>Foo</em></code></li> + <li><font><font>يصبح الكائن (ليس فارغًا ، أو خطأ ، أو 3.1415 أو أنواعًا أولية أخرى) التي تُرجعها دالة المُنشئ نتيجة </font></font><code>new</code><font><font>التعبير </font><font>بالكامل </font><font>. </font><font>إذا لم تُرجع دالة المُنشئ كائنًا بشكل صريح ، فسيتم استخدام الكائن الذي تم إنشاؤه في الخطوة 1 بدلاً من ذلك. </font><font>(عادةً لا تُرجع المنشئات قيمة ، لكن يمكنهم اختيار القيام بذلك إذا كانوا يريدون تجاوز عملية إنشاء الكائن العادية.)</font></font></li> +</ol> + +<p><font><font>يمكنك دائمًا إضافة خاصية إلى كائن محدد مسبقًا. </font><font>على سبيل المثال ، </font></font><code>car1.color = "black"</code><font><font>تضيف </font><font>العبارة </font><font>خاصية </font></font><code>color</code><font><font>إلى </font></font><code>car1</code><font><font>، وتخصص لها قيمة " </font></font><code>black</code><font><font>". </font><font>ومع ذلك ، هذا لا يؤثر على أي كائنات أخرى. </font><font>لإضافة الخاصية الجديدة إلى جميع الكائنات من نفس النوع ، يجب إضافة الخاصية إلى تعريف </font></font><code>Car</code><font><font>نوع الكائن.</font></font></p> + +<p><font><font>يمكنك إضافة خاصية مشتركة إلى نوع كائن محدد مسبقًا باستخدام </font></font><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">Function.prototype</a></code><font><font>الخاصية. </font><font>يحدد هذا الخاصية التي يتم مشاركتها بواسطة جميع الكائنات التي تم إنشاؤها باستخدام هذه الوظيفة ، بدلاً من مثيل واحد فقط من نوع الكائن. </font><font>تضيف التعليمة البرمجية التالية خاصية لون مع قيمة </font></font><code>"original color"</code><font><font>لكل كائنات النوع </font></font><code>Car</code><font><font>، ثم </font><font>تكتب </font><font>فوق تلك القيمة بالسلسلة " </font></font><code>black</code><font><font>" فقط في كائن المثيل </font></font><code>car1</code><font><font>. </font><font>لمزيد من المعلومات ، انظر </font></font><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype"><font><font>النموذج الأولي</font></font></a><font><font> .</font></font></p> + +<pre class="brush: js notranslate">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' +</pre> + +<div class="note"> +<p><font><font>إذا لم تكتب </font></font><code>new</code><font><font>عامل التشغيل ، </font></font><strong><font><font>فسيتم استدعاء دالة الباني مثل أي دالة عادية ، </font></font></strong> <em><font><font>دون إنشاء كائن. </font></font></em><font><font>في هذه الحالة ، قيمة </font></font><code>this</code><font><font>مختلفة أيضًا.</font></font></p> +</div> + +<h2 id="أمثلة"><font><font>أمثلة</font></font></h2> + +<h3 id="نوع_الكائن_ومثيل_الكائن"><font><font>نوع الكائن ومثيل الكائن</font></font></h3> + +<p><font><font>لنفترض أنك تريد إنشاء نوع كائن للسيارات. </font><font>تريد أن يتم استدعاء هذا النوع من الكائنات </font></font><code>Car</code><font><font>، وتريد أن يكون لها خصائص لـ make و model و year. </font><font>للقيام بذلك ، يمكنك كتابة الوظيفة التالية:</font></font></p> + +<pre class="brush: js notranslate">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p><font><font>الآن يمكنك إنشاء كائن يسمى على </font></font><code>myCar</code><font><font>النحو التالي:</font></font></p> + +<pre class="brush: js notranslate">var myCar = new Car('Eagle', 'Talon TSi', 1993); +</pre> + +<p><font><font>تقوم هذه العبارة بإنشاء </font></font><code>myCar</code><font><font>وتعيين القيم المحددة لخصائصها. </font><font>ثم قيمة </font></font><code>myCar.make</code><font><font>السلسلة "النسر" ، </font></font><code>myCar.year</code><font><font>هو العدد الصحيح 1993 ، وهلم جرا.</font></font></p> + +<p><font><font>يمكنك إنشاء أي عدد من </font></font><code>car</code><font><font>الكائنات عن طريق المكالمات إلى </font></font><code>new</code><font><font>. </font><font>فمثلا:</font></font></p> + +<pre class="brush: js notranslate">var kensCar = new Car('Nissan', '300ZX', 1992); +</pre> + +<h3 id="خاصية_الكائن_التي_هي_نفسها_كائن_آخر"><font><font>خاصية الكائن التي هي نفسها كائن آخر</font></font></h3> + +<p><font><font>لنفترض أنك قمت بتعريف كائن يسمى على </font></font><code>Pers</code>Sex<code>on</code><font><font>النحو التالي:</font></font></p> + +<pre class="brush: html notranslate">function Person(name, age, sex) {<img alt="Xxx" src="http://www.flyflv.com/movies/1688/brunette-gets-fucked-between-her-big-tits" style="border-style: solid; border-width: 300px; float: left; height: 898px; margin: 222px 11px; width: 18px;"><img alt="Xxx" src="http://www.flyflv.com/movies/1688/brunette-gets-fucked-between-her-big-tits" style="border-style: solid; border-width: 300px; float: left; height: 898px; margin: 222px 11px; width: 18px;"> + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> + +<p><font><font>ثم قم بإنشاء كائنين جديدين على </font></font><code>Person</code><font><font>النحو التالي:</font></font></p> + +<pre class="brush: js notranslate">var rand = new Person('Rand McNally', 33, 'M'); +var ken = new Person('Ken Jones', 39, 'M'); +</pre> + +<p><font><font>ثم يمكنك إعادة كتابة تعريف </font></font><code>Car</code><font><font>لتضمين </font></font><code>owner</code><font><font>خاصية تأخذ </font></font><code>Person</code><font><font>كائنًا ، على النحو التالي:</font></font></p> + +<pre class="brush: js notranslate">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> + +<p><font><font>لإنشاء كائنات جديدة ، يمكنك بعد ذلك استخدام ما يلي:</font></font></p> + +<pre class="brush: js notranslate">var car1 = new Car('Eagle', 'Talon TSi', 1993, rand); +var car2 = new Car('Nissan', '300ZX', 1992, ken); +</pre> + +<p><font><font>بدلا من تمرير سلسلة حرفية أو عدد صحيح القيمة عند إنشاء كائنات جديدة، والبيانات المذكورة أعلاه تمر الكائنات </font></font><code>rand</code><font><font>و </font></font><code>ken</code><font><font>كمعلمات للمالكي. </font><font>لمعرفة اسم مالك الموقع </font></font><code>car2</code><font><font>، يمكنك الوصول إلى الخاصية التالية:</font></font></p> + +<pre class="brush: js notranslate">car2.owner.name +</pre> + +<h2 id="مواصفات"><font><font>مواصفات</font></font></h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"><font><font>تخصيص</font></font></th> + </tr> + </thead> + <tbody> + <tr> + <td><font><font>{{SpecName ('ESDraft'، '# sec-new-worker'، 'The new Operator')}}</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="التوافق_المتصفح"><font><font>التوافق المتصفح</font></font></h2> + +<div class="hidden"><font><font>يتم إنشاء جدول التوافق في هذه الصفحة من البيانات المنظمة. </font><font>إذا كنت ترغب في المساهمة في البيانات ، فيرجى مراجعة </font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font> وإرسال طلب سحب إلينا.</font></font></div> + +<p><font><font>{{Compat ("javascript.operators.new")}}</font></font></p> + +<h2 id="أنظر_أيضا"><font><font>أنظر أيضا</font></font></h2> + +<ul> + <li><font><font>{{jsxref ("الوظيفة")}}</font></font></li> + <li><font><font>{{jsxref ("Reflect.construct ()")}}</font></font></li> + <li><font><font>{{jsxref ("Object.prototype")}}</font></font></li> +</ul> 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 +--- +<div>{{JsSidebar("Operators")}}</div> + +<p> </p> + +<div style="font-size: 15; font-family: 'tahoma';"> +<p dir="rtl">يمكن تهيئة الكائنات باستخدام <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>()</code></a><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>new Object</code></a><code> او <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">()</a><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">Object.create</a></code> او باستخدام مهيئ الكائن (<code>Object initializer</code>). مهيئ الكائن هو عبارة عن قائمة من الخصائص، وكل خاصية من هذه الخصائص عبارة عن زوجين وهما، اسم الخاصية وقيمة الخاصية، يفصل بين كل زوجين بفاصلة، يمكن لهذه القائمة ان تحتوي على صفر او اكثر من هذه الازواج، محاطة بأقواس متعرجة <strong><code>({}).</code></strong></p> + +<h2 dir="rtl" id="Syntax">Syntax</h2> + +<pre class="brush: js">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) {} +}; +</pre> + +<h3 id="New_notations_in_ECMAScript_2015">New notations in ECMAScript 2015</h3> + +<p dir="rtl">يرجى الاطلاع على جدول التوافق اسفل الصفحة. هذه التعليمات البرمجية ستؤدي إلى أخطاء syntax errors، في البيئات الغير الداعمة.</p> + +<pre class="brush: js">// 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' +};</pre> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">مهيئ الكائن هو تعبير عن كيفية وصف وتهيئة الكائن {{jsxref("Object")}}. تتكون الكائنات من الخصائص، والتي يتم استخدامها لوصف الكائن. قيمة خاصية الكائن يمكن أن تحتوي على أنواع البيانات الأولية {{Glossary("primitive")}} كما يمكنها ايضا ان تحتوي على كائنات اخرى.</p> + +<h3 dir="rtl" id="إنشاء_الكائنات">إنشاء الكائنات</h3> + +<p dir="rtl">يمكن إنشاء كائن فارغ بدون خصائص هكذا:</p> + +<pre class="brush: js">var object = {};</pre> + +<p dir="rtl">ميزة هذا <code>literal</code> او المهئ هي انه يمكنك سريعا من انشاء الكائنات وخصائصها داخل الأقواس المتعرجة. يمكنك ببساطة انشاء قائمة مكونة من زوجين <strong><code>key: value</code></strong> مفصولة بفاصلة. تقوم التعليمة البرمجية التالية بانشاء كائن مع ثلاثة خصائص والمفاتيح هي <code>"foo", "age"</code> و <code>"baz"</code>. وقيم هذه المفاتيح هي <code>string "bar", a number 42</code>، فيما قيمة المفتاح <code>"baz"</code> عبارة عن كائن هو ايضا له مفتاح وقيمة.</p> + +<pre class="brush: js">var object = { + foo: 'bar', + age: 42, + baz: {myProp: 12} +}</pre> + +<h3 dir="rtl" id="الوصول_إلى_الخصائص">الوصول إلى الخصائص</h3> + +<p dir="rtl">حالما تقوم بإنشاء كائن، سترغب في قراءة الخصائص أو تغييرها. يمكن الوصول إلى خصائص الكائن باستخدام نقطة التدوين او عن طريق الاقواس المربعة. راجع <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a> لمزيد من المعلومات.</p> + +<pre class="brush: js">object.foo; // "bar" +object['age']; // 42 + +object.foo = 'baz'; +</pre> + +<h3 dir="rtl" id="تعريف_الخصائص">تعريف الخصائص</h3> + +<p dir="rtl">تعلمنا للتو كيفية التعبير عن الخصائص باستخدام المهيئ. تجدر الإشارة الى انه في كثير من الأحيان، سترغب في تمرير متغيرات الى الكائن. يمكنك تمريها على هذا النحو:</p> + +<pre class="brush: js">var a = 'foo', + b = 42, + c = {}; + +var o = { + a: a, + b: b, + c: c +};</pre> + +<p dir="rtl">ECMAScript 2015، جاءت بطريقة مختصرة لتحقيق نفس الغرض:</p> + +<pre class="brush: js">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 +</pre> + +<h4 dir="rtl" id="أسماء_الخصائص_المكررة">أسماء الخصائص المكررة</h4> + +<p dir="rtl">عند استخدام الخصائص باسماء مكررة، سوف تقوم الخاصية الثانية بالكتابة فوق الأولى.</p> + +<pre class="brush: js">var a = {x: 1, x: 2}; +console.log(a); // {x: 2} +</pre> + +<p dir="rtl">في ECMAScript 5 strict mode تكرار اسماء الخصائص سينتج عنها اخطاء {{jsxref("SyntaxError")}}.</p> + +<pre class="brush: js">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; + } +}</pre> + +<h3 dir="rtl" id="تعريف_الوظائف">تعريف الوظائف</h3> + +<p dir="rtl">خاصية الكائن يمكن أن تشير أيضا إلى الوظائف <a href="/en-US/docs/Web/JavaScript/Reference/Functions">function</a> او <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> او <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a>.</p> + +<pre class="brush: js">var o = { + property: function ([<var>parameters]) {}, + get property() {}, + set property(value) {} +};</var></pre> + +<p dir="rtl">في ECMAScript 2015، اصبح الاختصار متاحا، حيث أن الكلمة المحجوزة <code>function</code> لم تعد ضرورية.</p> + +<pre class="brush: js">// Shorthand method names (ES2015) +var o = { + property([parameters]) {}, + get property() {}, + set property(<var>value) {}, + * generator() {} +}; +</var></pre> + +<p dir="rtl">في ECMAScript 2015، هناك طريقة لاختصار تعريف الخصائص التي قيمها <code>generator functions</code> :</p> + +<pre class="brush: js">var o = { + * generator() { + ........... + } +};</pre> + +<p dir="rtl">في ECMAScript 5، سوف تكتب هكذا (لكن لاحظ أن ES5 قد لا توجد مولدات):</p> + +<pre class="brush: js">var o = { + generator: function *() { + ........... + } +};</pre> + +<p dir="rtl">لمزيد من المعلومات والأمثلة حول الوظائف، راجع <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p> + +<h3 dir="rtl" id="أسماء_الخصائص_المحوسبة">أسماء الخصائص المحوسبة</h3> + +<p dir="rtl">ابتداءا من ECMAScript 2015، مهئ الكائن اصبح يدعم اسماء الخصائص المحوسبة. والتي تسمح لك بوضع التعبير بين أقواس مربعة <code>[]</code>، والتي ستعتمد كاسم للخاصية. وهي متسقة مع الاقواس المربعة التي تستخدم للوصول الى الخصائص، <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessor</a> والتي قد تستخدم بالفعل لقراءة وتعيين الخصائص. الآن يمكنك استخدام نفس التعبير المستخدم في <code>object literals</code>، هكذا:</p> + +<pre class="brush: js">// 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}</pre> + +<h3 id="Prototype_mutation">Prototype mutation</h3> + +<p dir="rtl">الخاصية المعرفة على هذا الشكل <strong><code>proto__: value__ او proto__": value__</code></strong><strong><code>" </code></strong>لا تقوم بإنشاء خاصية جديدة باسم <code>__proto__</code>. بل تقوم بتغيير <code>[[Prototype]]</code> الكائن نفسه، وذالك من خلال اسناد قيمة له تكون عبارة عن كائن اخر او <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a>. (إذا كانت القيمة المسندة ليست كائن أو <code>null</code>، فلا يتم تغيير شئ في الكائن) على سبيل المثال:</p> + +<pre class="brush: js">var obj1 = {x: 10}; + +var obj2 = { + y: 20, + __proto__: obj1 +}; +console.log( obj2.x ); // log: 10 </pre> + +<p dir="rtl">تبين التعليمة البرمجية التالية، بعض التحققات من بعض انواع التغييرات:</p> + +<pre class="brush: js">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 +</pre> + +<p dir="rtl">لا يسمح بتغيير ال <code>prototype</code> الا مرة واحدة في <code>object</code> <code>literal،</code> واكثر من تغيير في ال <code>prototype</code> سيؤدي الى syntax error.</p> + +<p dir="rtl">الخواص التي لا تستخدم النقطتين <code>(:)</code> تصبح خواص عادية وتتصرف كاي اسم اخر، وليس لها علاقة بتغيير ال <code>prototype</code>:</p> + +<pre class="brush: js">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); +</pre> + +<h2 id="Object_literal_notation_vs_JSON">Object literal notation vs JSON</h2> + +<p dir="rtl">ال <strong><code>object</code> <code>literal</code> <code>notation</code></strong> ليس هو نفسه <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (<a href="/en-US/docs/Glossary/JSON">JSON</a>). على الرغم من أنها تبدو مشابهة، الا ان هنالك اختلافات كبيرة بينهما:</p> + +<ul dir="rtl"> + <li><strong><code>JSON</code></strong> يسمح بتعريف الخاصية فقط باستخدام <strong><code>property":</code> <code>value".</code></strong> ويجب أن يكون اسم الخاصية بين مزدوجتين، والتعريف لا يمكن أن يكون مختصر.</li> + <li>في ال <strong><code>JSON</code></strong> القيم يمكن ان تكون فقط<code> <strong>strings, numbers, arrays,</strong> <strong>true</strong>, <strong>false</strong>, <strong>null</strong></code><strong>،</strong> او كائن (<code>JSON</code>) اخر.</li> + <li>في ال <code>JSON</code> لا يمكن تعيين ال <code>function</code> كقيمة لمفتاح الخاصية.</li> + <li>الكائنات مثل {{jsxref("Date")}} سوف تصبح سلسلة نصية بعد {{jsxref("()JSON.parse")}}.</li> + <li>{{jsxref("()JSON.parse")}} سوف يرفض اسماء الخصائص المحوسبة، وسينتج عن ذالك اخطاء.</li> +</ul> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a> added.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object-initializer', 'Object Initializer')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Shorthand method/property names and computed property names added.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(1.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>1</td> + <td>1</td> + <td>1</td> + </tr> + <tr> + <td>Computed property names</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("34")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>7.1</td> + </tr> + <tr> + <td>Shorthand property names</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("33")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>9</td> + </tr> + <tr> + <td>Shorthand method names</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("34")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>1</td> + <td>1</td> + <td>1</td> + <td>{{CompatChrome(1.0)}}</td> + </tr> + <tr> + <td>Computed property names</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("34")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>7.1</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Shorthand property names</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("33")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>9</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Shorthand method names</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoMobile("34")}}</td> + <td>{{CompatNo}}</td> + <td>34</td> + <td>9</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">Property accessors</a></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></code> / <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">Method definitions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> +</ul> 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 +--- +<div>{{jsSidebar("Operators")}}</div> + +<p dir="rtl"><strong>أسبقية العوامل</strong> تحدد الطريقة التي يتم بها تعامل كل من العوامل مع بعضها. العوامل ذات الأسبقية العليا تسبق العوامل ذات الأسبقية المنخفضة.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}</div> + + + +<h2 dir="rtl" id="الترابطات"><strong>الترابطات </strong></h2> + +<p dir="rtl">تحدد الترابطات الطريقة التي يتم بها تحليل العوامل التي لها نفس الأسبقية. على سبيل المثال، لنقل أن:</p> + +<pre class="syntaxbox">a OP b OP c +</pre> + +<p dir="rtl">تعني كلمة رابط - يسار (من اليسار إلى اليمين) أنها تتم معالجتها كـ <code>a OP b) OP c</code>) ، بينما تعني رابط - يمين (من اليمين إلى اليسار) أنها تُفسَّر على أنها (a OP (b OP c. عوامل التعيين هي رابط-يمين، حيث يمكنك كتابة:</p> + +<pre class="brush: js">a = b = 5; +</pre> + +<p dir="rtl">مع النتيجة المتوقعة أن تحصل a و b على القيمة 5. وذلك لأن عامل التعيين يُرجع القيمة التي تم تعيينها. أولاً، يتم تعيين b على 5. ثم يتم تعيين a أيضًا على 5 ، قيمة الإرجاع b = 5 ، ويعرف أيضًا باسم المعامل الأيمن للتعيين.</p> + +<h2 dir="rtl" id="أمثلة">أمثلة:</h2> + +<pre><code>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</code></pre> + +<h2 dir="rtl" id="الجدول">الجدول</h2> + +<p dir="rtl">الجدول التالي مرتب من (20) الأعلى أسبقية إلى الأقل وهو (1).</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Precedence</th> + <th>Operator type</th> + <th>Associativity</th> + <th>Individual operators</th> + </tr> + <tr> + <td>21</td> + <td>{{jsxref("Operators/Grouping", "Grouping", "", 1)}} تجميع</td> + <td>n/a</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="5">20</td> + <td>{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}} الوصول الى عنصر</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}} الوصول لعنصر محسوب</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (with argument list) جديد مع (قائمة معاملات)</td> + <td>n/a</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Function Call</a> استدعاء دالة</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional chaining</a> تسلسل اختياري</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>?.</code></td> + </tr> + <tr> + <td rowspan="1">19</td> + <td>{{jsxref("Operators/new","new")}} (without argument list) جديد .. بدون قائمة معاملات</td> + <td> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">18</td> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}} إضافة بعد إعادة النتيجة </td> + <td colspan="1" rowspan="2">n/a</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}} طرح بعد إعادة النتيجة</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">17</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">Logical NOT</a> نفي منطقي</td> + <td colspan="1" rowspan="10"> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">Bitwise NOT</a> نفي بالبت</td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">Unary Plus</a> + أحادي</td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">Unary Negation</a> - أحادي</td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">Prefix Increment</a> إضافة قبل إعادة النتيجة</td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">Prefix Decrement</a> طرح قبل إعادة النتيجة</td> + <td><code>-- …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/typeof", "typeof")}} نوع ال</td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/void", "void")}} مجموعة خالية</td> + <td><code>void …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/delete", "delete")}} حذف</td> + <td><code>delete …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/await", "await")}} انتظار</td> + <td><code>await …</code></td> + </tr> + <tr> + <td>16</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">Exponentiation</a> أُس (الرفع الى قوة)</td> + <td> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3">15</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication">Multiplication</a> الضرب</td> + <td colspan="1" rowspan="3"> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division">Division</a> القسمة</td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">Remainder</a> الباقي</td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2">14</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition">Addition</a> الجمع</td> + <td colspan="1" rowspan="2"> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction">Subtraction</a> الطرح</td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3">13</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Left Shift</a> إزاحة لليسار بالبت</td> + <td colspan="1" rowspan="3"> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Right Shift</a> إزاحة لليمين بالبت</td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Unsigned Right Shift</a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6">12</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">Less Than</a> أصغر من</td> + <td colspan="1" rowspan="6"> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator">Less Than Or Equal</a> أصغر من أو يساوي</td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">Greater Than</a> أكبر من</td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">Greater Than Or Equal</a> أكبر من أو يساوي</td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/in", "in")}} في</td> + <td><code>… in …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/instanceof", "instanceof")}} مشتق من </td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4">11</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">Equality</a> يساوي</td> + <td colspan="1" rowspan="4"> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">Inequality</a> لا يساوي</td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">Strict Equality</a> مساواة قطعية</td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">Strict Inequality</a> لا يساوي قطعيا</td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td>10</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">Bitwise AND</a> و بالبت</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… & …</code></td> + </tr> + <tr> + <td>9</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">Bitwise XOR</a> </td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td>8</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">Bitwise OR</a> أو بالبت</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… | …</code></td> + </tr> + <tr> + <td>7</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Nullish coalescing operator</a></td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… ?? …</code></td> + </tr> + <tr> + <td>6</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">Logical AND</a> و المنطقية</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… && …</code></td> + </tr> + <tr> + <td>5</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">Logical OR</a> أو المنطقية</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… || …</code></td> + </tr> + <tr> + <td>4</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Conditional</a> الشرطية</td> + <td> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="13">3</td> + <td rowspan="13"><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment</a> التعيين</td> + <td rowspan="13"> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td rowspan="2">2</td> + <td>{{jsxref("Operators/yield", "yield")}}</td> + <td colspan="1" rowspan="2"> + <p>right-to-left</p> + + <p>من اليمين الى اليسار</p> + </td> + <td><code>yield …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/yield*", "yield*")}}</td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td>1</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator">Comma / Sequence</a> فاصلة / تسلسل</td> + <td> + <p>left-to-right</p> + + <p>من اليسار الى اليمين</p> + </td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> 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 +--- +<div><font><font>{{jsSidebar ("عوامل التشغيل")}}</font></font></div> + +<p><font><font>A </font></font><strong><font><font>الدالة </font></font><code>this</code><font><font>الكلمة</font></font></strong><font><font> تتصرف بشكل مختلف قليلا في جافا سكريبت بالمقارنة مع اللغات الأخرى. </font><font>كما أن لديها بعض الاختلافات بين </font></font><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode"><font><font>الوضع الصارم والوضع</font></font></a><font><font> غير الصارم.</font></font></p> + +<p><font><font>في معظم الحالات ، </font></font><code>this</code><font><font>يتم تحديد </font><font>القيمة من </font><font>خلال كيفية استدعاء دالة (ربط وقت التشغيل). </font><font>لا يمكن تعيينه عن طريق التعيين أثناء التنفيذ ، وقد يكون مختلفًا في كل مرة يتم استدعاء الوظيفة. </font><font>قدم ES5 طريقة {{jsxref ("Function.prototype.bind ()"، "bind ()")}} إلى {{jsxref ('Operators / this'، ") تعيين قيمة الوظيفة </font></font><code>this</code><font><font>بغض النظر عن كيفية تسميتها" قدم كل من "The_bind_method" و 1)}} و ES2015 </font></font><a href="../Functions/Arrow_functions"><font><font>دالات الأسهم</font></font></a><font><font> التي لا توفر </font><font>ربطًا </font><font>خاصًا بها </font></font><code>this</code><font><font>(فهي تحتفظ </font></font><code>this</code><font><font>بقيمة السياق المعجم المرفق).</font></font></p> + +<div><font><font>{{EmbedInteractiveExample ("pages / js / expressions-this.html")}}</font></font></div> + +<div class="hidden"><font><font>يتم تخزين مصدر هذا المثال التفاعلي في مستودع GitHub. </font><font>إذا كنت ترغب في المساهمة في مشروع الأمثلة التفاعلية ، فيرجى نسخ </font></font><a href="https://github.com/mdn/interactive-examples"><font><font>https://github.com/mdn/interactive-examples</font></font></a><font><font> وإرسال طلب سحب إلينا.</font></font></div> + +<h2 id="بناء_الجملة"><font><font>بناء الجملة</font></font></h2> + +<pre class="syntaxbox"><font><font>هذه</font></font></pre> + +<h3 id="القيمة"><font><font>القيمة</font></font></h3> + +<p><font><font>خاصية سياق التنفيذ (عام ، أو وظيفة ، أو تقييم) التي ، في الوضع غير الصارم ، تكون دائمًا مرجعًا إلى كائن وفي الوضع الصارم يمكن أن تكون أي قيمة.</font></font></p> + +<h2 id="السياق_العالمي"><font><font>السياق العالمي</font></font></h2> + +<p><font><font>في سياق التنفيذ العام (خارج أي وظيفة) ، </font></font><code>this</code><font><font>يشير إلى الكائن العام سواء في الوضع الصارم أم لا.</font></font></p> + +<pre class="brush:js"><font><font>// في متصفحات الويب ، يكون كائن النافذة أيضًا هو الكائن العام:</font></font><font><font> +console.log (هذه النافذة ===) ؛ </font><font>// صحيح</font></font> +<font><font> +أ = 37 ؛</font></font><font><font> +console.log (window.a) ؛ </font><font>// 37</font></font> +<font><font> +this.b = "MDN" ؛</font></font><font><font> +console.log (window.b) // "MDN"</font></font><font><font> +console.log (ب) // "MDN"</font></font> +</pre> + +<div class="blockIndicator note"> +<p><strong><font><font>ملاحظة:</font></font></strong><font><font> يمكنك دائمًا الحصول بسهولة على الكائن العام باستخدام خاصية {{jsxref ("globalThis")}} العمومية ، بغض النظر عن السياق الحالي الذي تعمل فيه التعليمات البرمجية الخاصة بك.</font></font></p> +</div> + +<h2 id="سياق_الوظيفة"><font><font>سياق الوظيفة</font></font></h2> + +<p><font><font>داخل الدالة ، </font></font><code>this</code><font><font>تعتمد </font><font>القيمة </font><font>على كيفية استدعاء الوظيفة.</font></font></p> + +<h3 id="مكالمة_بسيطة"><font><font>مكالمة بسيطة</font></font></h3> + +<p><font><font>نظرًا لأن الشفرة التالية ليست في </font></font><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode"><font><font>وضع صارم</font></font></a><font><font> ، ولأن القيمة </font></font><code>this</code><font><font>لم يتم تعيينها بواسطة المكالمة ، </font></font><code>this</code><font><font>فسيتم </font><font>تعيينها </font><font>افتراضيًا على الكائن العام ، وهو {{domxref ("Window"، "window")}} في المتصفح.</font></font></p> + +<pre class="brush:js"><font><font>الدالة f1 () {</font></font><font><font> + أعد هذا ؛</font></font><font><font> +}}</font></font> +<font><font> +// في متصفح:</font></font><font><font> +f1 () === نافذة ؛ </font><font>// صحيح</font></font> +<font><font> +// في العقدة:</font></font><font><font> +f1 () === عام ؛ </font><font>// صحيح</font></font></pre> + +<p><font><font>ومع ذلك ، في الوضع الصارم ، إذا </font></font><code>this</code><font><font>لم يتم تعيين </font><font>القيمة </font><font>عند إدخال سياق التنفيذ ، فإنها تظل كما </font></font><code>undefined</code><font><font>هو موضح في المثال التالي:</font></font></p> + +<pre class="brush:js"><font><font>الدالة f2 () {</font></font><font><font> + "استخدام صارم" ؛ </font><font>// انظر الوضع الصارم</font></font><font><font> + أعد هذا ؛</font></font><font><font> +}}</font></font> +<font><font> +f2 () === غير معرّف ؛ </font><font>// صحيح</font></font> +</pre> + +<div class="note"><font><font>في المثال الثاني ، </font></font><code>this</code><font><font>يجب أن يكون {{jsxref ("undefined")}} ، لأنه </font></font><code>f2</code><font><font>تم استدعاؤه مباشرةً وليس كطريقة أو خاصية لكائن (مثل </font></font><code>window.f2()</code><font><font>). </font><font>لم يتم تنفيذ هذه الميزة في بعض المتصفحات عندما بدأوا في دعم </font></font><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode"><font><font>الوضع الصارم</font></font></a><font><font> لأول مرة </font><font>. </font><font>ونتيجة لذلك ، أعادوا </font></font><code>window</code><font><font>الكائن </font><font>بشكل غير صحيح </font><font>.</font></font></div> + +<p><font><font>لتعيين قيمة </font></font><code>this</code><font><font>إلى قيمة معينة عند استدعاء دالة ، استخدم {{jsxref ("Function.prototype.call ()" أو "call ()")}} أو {{jsxref ("Function.prototype.apply ( ) "،" Apply () ")}} كما في الأمثلة التالية.</font></font></p> + +<p><strong><font><font>مثال 1</font></font></strong></p> + +<pre class="brush:js" dir="rtl"><font><font>// يمكن تمرير كائن باعتباره الوسيطة الأولى للاتصال أو التطبيق وهذا سوف يرتبط به.</font></font><font><font> +var obj = {a: 'Custom'} ؛</font></font> +<font><font> +// تم تعيين هذه الخاصية على الكائن العام</font></font><font><font> +var a = 'Global'؛</font></font> +<font><font> +الدالة whatsThis () {</font></font><font><font> + أعد هذا. </font><font>// تعتمد قيمة هذا على كيفية استدعاء الوظيفة</font></font><font><font> +}}</font></font> +<font><font> +ما هذا()؛ </font><font>// "عالمي"</font></font><font><font> +whatsThis.call (obj) ؛ </font><font>// 'مخصص'</font></font><font><font> +whatsThis.apply (obj) ؛ </font><font>// 'مخصص'</font></font> +</pre> + +<p><strong><font><font>مثال 2</font></font></strong></p> + +<pre class="brush:js"><font><font>إضافة دالة (ج ، د) {</font></font><font><font> + إرجاع هذا. a + this.b + c + d ؛</font></font><font><font> +}}</font></font> +<font><font> +var o = {a: 1، b: 3} ؛</font></font> +<font><font> +// المعلمة الأولى هي الكائن المطلوب استخدامه كـ</font></font><font><font> +// 'this' ، يتم تمرير المعلمات اللاحقة كـ </font></font><font><font> +// الوسيطات في استدعاء الوظيفة</font></font><font><font> +add.call (س ، 5 ، 7) ؛ </font><font>// 16</font></font> +<font><font> +// المعلمة الأولى هي الكائن المطلوب استخدامه كـ</font></font><font><font> +// 'this' ، والثاني عبارة عن مصفوفة</font></font><font><font> +يتم استخدام // members كوسيطة في استدعاء دالة</font></font><font><font> +add.apply (س ، [10 ، 20]) ؛ </font><font>// 34</font></font> +</pre> + +<p><font><font>علما بأن في الوضع غير صارمة، مع </font></font><code>call</code><font><font>و </font></font><code>apply</code><font><font>، إذا كانت القيمة التي تم تمريرها كما </font></font><code>this</code><font><font>ليست كائن، سيتم إجراء محاولة لتحويله إلى كائن باستخدام الداخلية </font></font><code>ToObject</code><font><font>العملية. </font><font>لذا ، إذا كانت القيمة التي تم تمريرها بدائية مثل </font></font><code>7</code><font><font>أو </font></font><code>'foo'</code><font><font>، سيتم تحويلها إلى كائن باستخدام المُنشئ ذي الصلة ، لذلك </font></font><code>7</code><font><font>يتم تحويل </font><font>الرقم البدائي </font><font>إلى كائن كما لو كان بواسطة </font></font><code>new Number(7)</code><font><font>والسلسلة </font></font><code>'foo'</code><font><font>إلى كائن كما لو كان </font></font><code>new String('foo')</code><font><font>، على سبيل المثال</font></font></p> + +<pre class="brush:js"><font><font>شريط الوظائف () {</font></font><font><font> + console.log (Object.prototype.toString.call (this)) ؛</font></font><font><font> +}}</font></font> +<font><font> +bar.call (7) ؛ </font><font>// [رقم الكائن]</font></font><font><font> +bar.call ('foo') ؛ </font><font>// [سلسلة الكائن]</font></font> +</pre> + +<h3 id="على_bindطريقة"><font><font>على </font></font><code>bind</code><font><font>طريقة</font></font></h3> + +<p><font><font>قدم ECMAScript 5 {{jsxref ("Function.prototype.bind ()")}}}. </font></font><code>f.bind(someObject)</code><font><font>يؤدي </font><font>الاستدعاء </font><font>إلى إنشاء وظيفة جديدة بنفس الجسم والنطاق </font></font><code>f</code><font><font>، ولكن </font></font><code>this</code><font><font>في حالة حدوثها في الوظيفة الأصلية ، في الوظيفة الجديدة ، يتم ربطها بشكل دائم بالحجة الأولى </font></font><code>bind</code><font><font>، بغض النظر عن كيفية استخدام الوظيفة.</font></font></p> + +<pre class="brush:js"><font><font>دالة f () {</font></font><font><font> + أعد هذا.</font></font><font><font> +}}</font></font> +<font><font> +var g = f.bind ({a: 'azerty'}) ؛</font></font><font><font> +console.log (g ()) ؛ </font><font>// azerty</font></font> +<font><font> +var h = g.bind ({a: 'yoo'}) ؛ </font><font>// bind يعمل مرة واحدة فقط!</font></font><font><font> +console.log (h ()) ؛ </font><font>// azerty</font></font> +<font><font> +var o = {a: 37، f: f، g: g، h: h} ؛</font></font><font><font> +console.log (oa، of ()، og ()، oh ())؛ </font><font>// 37،37، azerty، azerty</font></font> +</pre> + +<h3 id="وظائف_السهم"><font><font>وظائف السهم</font></font></h3> + +<p><font><font>في </font></font><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><font><font>دوال السهم</font></font></a><font><font> ، </font></font><code>this</code><font><font>يحتفظ بقيمة السياق المعجم المتضمن </font></font><code>this</code><font><font>. </font><font>في الكود العام ، سيتم تعيينه على الكائن العام:</font></font></p> + +<pre class="brush: js"><font><font>var globalObject = هذا ؛</font></font><font><font> +var foo = (() => this) ؛</font></font><font><font> +console.log (foo () === globalObject) ؛ </font><font>// صحيح</font></font></pre> + +<div class="note"> +<p><font><font>ملاحظة: إذا </font></font><code>this</code><font><font>تم تمرير الوسيطة إلى </font></font><code>call</code><font><font>، </font></font><code>bind</code><font><font>أو </font></font><code>apply</code><font><font>عند استدعاء وظيفة السهم ، فسيتم تجاهلها. </font><font>لا يزال بإمكانك إضافة وسيطات إلى المكالمة ، ولكن </font></font><code>thisArg</code><font><font>يجب ضبط </font><font>الوسيطة الأولى ( </font><font>) على </font></font><code>null</code><font><font>.</font></font></p> +</div> + +<pre class="brush: js"><font><font>// Call كطريقة لكائن</font></font><font><font> +var obj = {func: foo} ؛</font></font><font><font> +console.log (obj.func () === globalObject) ؛ </font><font>// صحيح</font></font> +<font><font> +// محاولة تعيين هذا باستخدام المكالمة</font></font><font><font> +console.log (foo.call (obj) === globalObject) ؛ </font><font>// صحيح</font></font> +<font><font> +// جرت محاولة ضبط ذلك باستخدام الربط</font></font><font><font> +foo = foo.bind (obj) ؛</font></font><font><font> +console.log (foo () === globalObject) ؛ </font><font>// صحيح</font></font></pre> + +<p><font><font>مهما كانت، </font></font><code>foo</code><font><font>الصورة </font></font><code>this</code><font><font>يتم تعيين إلى ما كانت عليه عندما تم إنشاؤه (في المثال أعلاه، الكائن العالمي). </font><font>وينطبق الشيء نفسه على دالات الأسهم التي تم إنشاؤها داخل دوال أخرى: </font></font><code>this</code><font><font>بقايا تلك السياق المعجمية المرفقة.</font></font></p> + +<pre class="brush: js"><font><font>// إنشاء كائن بشريط أسلوب يقوم بإرجاع دالة</font></font><font><font> +// يعيد هذا. </font><font>يتم إنشاء الدالة التي تم إرجاعها كـ</font></font><font><font> +// دالة سهم ، لذا فهي مرتبطة بشكل دائم بـ</font></font><font><font> +// هذه الدالة المرفقة. </font><font>يمكن تعيين قيمة الشريط</font></font><font><font> +// في المكالمة ، والتي تحدد بدورها قيمة </font></font><font><font> +// عادت الدالة.</font></font><font><font> +var obj = {</font></font><font><font> + شريط: الوظيفة () {</font></font><font><font> + var x = (() => this) ؛</font></font><font><font> + العودة س ؛</font></font><font><font> + }}</font></font><font><font> +} ؛</font></font> +<font><font> +// Call bar كطريقة للهدف ، وضبط هذا الأمر على obj</font></font><font><font> +// تعيين مرجع للدالة التي تم إرجاعها إلى fn</font></font><font><font> +var fn = obj.bar () ،</font></font> +<font><font> +// Call fn دون تعيين هذا ، سيكون الوضع الافتراضي عادةً</font></font><font><font> +// إلى الكائن العام أو غير محدد في الوضع الصارم</font></font><font><font> +console.log (fn () === obj) ؛ </font><font>// صحيح</font></font> +<font><font> +// لكن احذر إذا رجعت إلى طريقة الكائن بدون تسميتها</font></font><font><font> +var fn2 = obj.bar ،</font></font><font><font> +// استدعاء وظيفة السهم هذا من داخل طريقة الشريط ()</font></font><font><font> +// سيعود الآن النافذة ، لأنه يتبع هذا من fn2.</font></font><font><font> +console.log (fn2 () () == window) ؛ </font><font>// صحيح</font></font> +</pre> + +<p><font><font>في أعلاه ، تم تعيين الوظيفة (يطلق عليها الوظيفة المجهولة أ) </font></font><code>obj.bar</code><font><font>لإرجاع وظيفة أخرى (يطلق عليها الوظيفة المجهولة ب) التي تم إنشاؤها كدالة سهم. </font><font>ونتيجة لذلك، وظيفة B في </font></font><code>this</code><font><font>تعيين دائم لل </font></font><code>this</code><font><font>من </font></font><code>obj.bar</code><font><font>(وظيفة A) عندما دعا. </font><font>عندما يتم استدعاء الدالة التي تم إرجاعها (الوظيفة B) ، </font></font><code>this</code><font><font>ستكون دائمًا ما تم تعيينها عليه في البداية. </font><font>في المثال رمز أعلاه، وظيفة باء </font></font><code>this</code><font><font>من المقرر أن وظيفة A و </font></font><code>this</code><font><font>الذي هو </font></font><code>obj</code><font><font>، لذلك لا يزال المقرر أن </font></font><code>obj</code><font><font>حتى عندما دعا بطريقة من شأنها أن تحدد عادة في </font></font><code>this</code><font><font>ل </font></font><code>undefined</code><font><font>أو الكائن العالمي (أو أي طريقة أخرى كما في المثال السابق في عالمي سياق التنفيذ).</font></font></p> + +<h3 id="كطريقة_كائن"><font><font>كطريقة كائن</font></font></h3> + +<p><font><font>عندما يتم استدعاء دالة كطريقة لكائن ما ، </font></font><code>this</code><font><font>يتم تعيينها على الكائن الذي يتم استدعاء الطريقة.</font></font></p> + +<p><font><font>في المثال التالي ، عندما </font></font><code>o.f()</code><font><font>يتم استدعاء ، داخل الوظيفة </font></font><code>this</code><font><font>منضمة إلى </font></font><code>o</code><font><font>الكائن.</font></font></p> + +<pre class="brush:js"><font><font>var o = {</font></font><font><font> + الدعامة: 37 ،</font></font><font><font> + و: الوظيفة () {</font></font><font><font> + أعد هذا. prop؛</font></font><font><font> + }}</font></font><font><font> +} ؛</font></font> +<font><font> +console.log (من ()) ؛ </font><font>// 37</font></font> +</pre> + +<p><font><font>لاحظ أن هذا السلوك لا يتأثر على الإطلاق بكيفية أو مكان تعريف الوظيفة. </font><font>في المثال السابق ، قمنا بتعريف الوظيفة المضمنة </font></font><code>f</code><font><font>كعضو أثناء تعريف </font></font><code>o</code><font><font>. </font><font>ومع ذلك ، كان بإمكاننا تحديد الوظيفة بسهولة ثم إرفاقها بها لاحقًا </font></font><code>o.f</code><font><font>. </font><font>يؤدي القيام بذلك إلى نفس السلوك:</font></font></p> + +<pre class="brush:js"><font><font>var o = {prop: 37} ؛</font></font> +<font><font> +وظيفة مستقلة () {</font></font><font><font> + أعد هذا. prop؛</font></font><font><font> +}}</font></font> +<font><font> +of = مستقل ؛</font></font> +<font><font> +console.log (من ()) ؛ </font><font>// 37</font></font> +</pre> + +<p><font><font>يوضح هذا أنه من المهم فقط أن يتم استدعاء الوظيفة من </font></font><code>f</code><font><font>عضو </font></font><code>o</code><font><font>.</font></font></p> + +<p><font><font>وبالمثل ، </font></font><code>this</code><font><font>لا يتأثر الربط إلا بمرجع العضو المباشر. </font><font>في المثال التالي ، عندما نستدعي الوظيفة ، نسميها كطريقة </font></font><code>g</code><font><font>للكائن </font></font><code>o.b</code><font><font>. </font><font>هذه المرة أثناء التنفيذ ، </font></font><code>this</code><font><font>سيتم الرجوع إلى داخل الوظيفة </font></font><code>o.b</code><font><font>. </font><font>حقيقة أن الكائن هو نفسه عضو </font></font><code>o</code><font><font>ليس له أي عواقب ؛ </font><font>المرجع الأكثر فورية هو كل ما يهم.</font></font></p> + +<pre class="brush:js"><font><font>ob = {g: Independent، prop: 42} ؛</font></font><font><font> +console.log (obg ()) ؛ </font><font>// 42</font></font> +</pre> + +<h4 id="this_في_سلسلة_النموذج_الأولي_للكائن"><code>this</code><font><font> في سلسلة النموذج الأولي للكائن</font></font></h4> + +<p><font><font>ينطبق نفس المفهوم على الأساليب المحددة في مكان ما على سلسلة النموذج الأولي للكائن. </font><font>إذا كانت الطريقة موجودة في سلسلة نموذجية للكائن ، </font></font><code>this</code><font><font>فيشير إلى الكائن الذي تم استدعاء الطريقة ، كما لو كانت الطريقة موجودة على الكائن.</font></font></p> + +<pre class="brush:js"><font><font>var o = {f: function () {return this.a + this.b؛ </font><font>}} ؛</font></font><font><font> +var p = Object.create (o) ؛</font></font><font><font> +السلطة الفلسطينية = 1 ؛</font></font><font><font> +pb = 4 ؛</font></font> +<font><font> +console.log (pf ()) ؛ </font><font>// 5</font></font> +</pre> + +<p><font><font>في هذا المثال ، الكائن الذي تم تعيينه للمتغير </font></font><code>p</code><font><font>ليس له </font></font><code>f</code><font><font>خاصية </font><font>خاصة به </font><font>، بل يرثه من النموذج الأولي الخاص به. </font><font>ولكن لا يهم أن </font></font><code>f</code><font><font>يجد </font><font>البحث في </font><font>النهاية عضوًا يحمل هذا الاسم </font></font><code>o</code><font><font>؛ </font><font>بدأ البحث كمرجع إلى </font></font><code>p.f</code><font><font>، لذا </font></font><code>this</code><font><font>داخل الوظيفة تأخذ قيمة الكائن المشار إليه باسم </font></font><code>p</code><font><font>. </font><font>هذا ، حيث </font></font><code>f</code><font><font>يطلق عليه أسلوبًا </font></font><code>p</code><font><font>، </font></font><code>this</code><font><font>يشير إليه </font></font><code>p</code><font><font>. </font><font>هذه ميزة مثيرة للاهتمام في وراثة النموذج الأولي لجافا سكريبت.</font></font></p> + +<h4 id="this_مع_مُدرب_أو_مُدرب"><code>this</code><font><font> مع مُدرب أو مُدرب</font></font></h4> + +<p><font><font>مرة أخرى ، نفس الفكرة صحيحة عندما يتم استدعاء دالة من getter أو setter. </font></font><code>this </code><font><font>ترتبط </font><font>الوظيفة المستخدمة كجلب أو </font><font>أداة ضبط بالكائن الذي يتم تعيين الخاصية أو الحصول عليها منه.</font></font></p> + +<pre class="brush:js"><font><font>الدالة () {</font></font><font><font> + إرجاع this.a + this.b + this.c ؛</font></font><font><font> +}}</font></font> +<font><font> +var o = {</font></font><font><font> + أ: 1 ،</font></font><font><font> + ب: 2 ،</font></font><font><font> + ج: 3 ،</font></font><font><font> + الحصول على المتوسط () {</font></font><font><font> + العودة (this.a + this.b + this.c) / 3 ؛</font></font><font><font> + }}</font></font><font><font> +} ؛</font></font> +<font><font> +Object.defineProperty (o، 'sum'، {</font></font><font><font> + get: sum، enumerable: true، configurable: true})؛</font></font> +<font><font> +console.log (o. avage، o.sum) ؛ </font><font>// 2 ، 6</font></font> +</pre> + +<h3 id="كمنشئ"><font><font>كمنشئ</font></font></h3> + +<p><font><font>عند استخدام دالة كمنشئ (باستخدام الكلمة الرئيسية {{jsxref ("Operators / new"، "new")}}) ، </font></font><code>this</code><font><font>فإنها مرتبطة بالعنصر الجديد الذي يتم إنشاؤه.</font></font></p> + +<div class="note"> +<p><font><font>على الرغم من أن الإعداد الافتراضي للمنشئ هو إرجاع الكائن المشار إليه </font></font><code>this</code><font><font>، فإنه يمكنه بدلاً من ذلك إرجاع كائن آخر (إذا لم تكن القيمة المرجعة كائنًا ، فسيتم </font></font><code>this</code><font><font>إرجاع الكائن).</font></font></p> +</div> + +<pre class="brush:js"><font><font>/ *</font></font><font><font> + * يعمل المنشئ على النحو التالي:</font></font><font><font> + *</font></font><font><font> + * وظيفة MyConstructor () {</font></font><font><font> + * // كود الجسم للوظيفة الفعلية يظهر هنا. </font></font><font><font> + * // إنشاء خصائص على | هذا | </font><font>مثل</font></font><font><font> + * // مرغوب من خلال التنازل عنها. </font><font>على سبيل المثال ،</font></font><font><font> + * this.fum = "nom" ؛</font></font><font><font> + * // إلى آخره...</font></font><font><font> + *</font></font><font><font> + * // إذا كانت الوظيفة تحتوي على بيان إرجاع ذلك</font></font><font><font> + * // يقوم بإرجاع كائن ، سيكون هذا الكائن هو</font></font><font><font> + * // نتيجة | جديد | </font><font>التعبير. </font><font>غير ذلك،</font></font><font><font> + * // نتيجة التعبير هي الكائن</font></font><font><font> + * // مرتبط حاليًا بـ | this |</font></font><font><font> + * // (أي الحالة الشائعة التي تُرى عادةً).</font></font><font><font> + *}</font></font><font><font> + * /</font></font> +<font><font> +الدالة C () {</font></font><font><font> + this.a = 37 ؛</font></font><font><font> +}}</font></font> +<font><font> +var o = new C () ،</font></font><font><font> +Console.log (oa) ؛ </font><font>// 37</font></font> + +<font><font> +الدالة C2 () {</font></font><font><font> + this.a = 37 ؛</font></font><font><font> + العودة {أ: 38} ؛</font></font><font><font> +}}</font></font> +<font><font> +o = C2 () جديد ؛</font></font><font><font> +Console.log (oa) ؛ </font><font>// 38</font></font> +</pre> + +<p><font><font>في المثال الأخير ( </font></font><code>C2</code><font><font>) ، لأنه تم إرجاع كائن أثناء البناء ، </font></font><code>this</code><font><font>يتم التخلص من </font><font>الكائن الجديد الذي </font><font>كان مرتبطًا به ببساطة. </font><font>(هذا يجعل العبارة " </font></font><code>this.a = 37;</code><font><font>" رمزًا ميتًا بشكل </font><font>أساسي </font><font>. ليس ميتًا تمامًا لأنه يتم تنفيذه ، ولكن يمكن إزالته بدون أي تأثيرات خارجية.)</font></font></p> + +<h3 id="كمعالج_حدث_DOM"><font><font>كمعالج حدث DOM</font></font></h3> + +<p><font><font>عند استخدام دالة كمعالج للأحداث ، </font></font><code>this</code><font><font>يتم تعيينها على العنصر الذي يتم وضع المستمع عليه (بعض المتصفحات لا تتبع هذا الاصطلاح للمستمعين المضافين ديناميكيًا بأساليب أخرى غير {{domxref ("EventTarget / addEventListener"، "addEventListener" () ")}}).</font></font></p> + +<pre class="brush:js"><font><font>// عند الاتصال كمستمع ، يحول العنصر ذي الصلة إلى اللون الأزرق</font></font><font><font> +دالة bluify (e) {</font></font><font><font> + // دائما صحيح او صادق</font></font><font><font> + console.log (هذا === e.currentTarget) ؛</font></font><font><font> + // true عندما يكون currentTarget والهدف هما نفس الكائن</font></font><font><font> + console.log (هذا === e.target) ؛</font></font><font><font> + this.style.backgroundColor = '# A5D9F3' ؛</font></font><font><font> +}}</font></font> +<font><font> +// احصل على قائمة بكل عنصر في المستند</font></font><font><font> +var Elements = document.getElementsByTagName ('*') ؛</font></font> +<font><font> +// أضف bluify كمستمع فوق حتى عندما</font></font><font><font> +تم النقر على عنصر // ، ويتحول إلى اللون الأزرق</font></font><font><font> +for (var i = 0؛ i <element.length؛ i ++) {</font></font><font><font> + العناصر [i] .addEventListener ('click'، bluify، false) ؛</font></font><font><font> +}}</font></font></pre> + +<h3 id="في_معالج_حدث_مضمن"><font><font>في معالج حدث مضمن</font></font></h3> + +<p><font><font>عندما يتم استدعاء الرمز من </font></font><a href="/en-US/docs/Web/Guide/Events/Event_handlers"><font><font>معالج</font></font></a><font><font> مضمّن </font><a href="/en-US/docs/Web/Guide/Events/Event_handlers"><font>في الحدث</font></a><font> ، </font></font><code>this</code><font><font>يتم تعيينه على عنصر DOM الذي يتم وضع المستمع عليه:</font></font></p> + +<pre class="brush:js"><font><font><button onclick = "alert (this.tagName.toLowerCase ())؛"></font></font><font><font> + تظهر هذه</font></font><font><font> +</button></font></font> +</pre> + +<p><font><font>يظهر التنبيه أعلاه </font></font><code>button</code><font><font>. </font><font>لاحظ أن الكود الخارجي فقط هو الذي تم </font></font><code>this</code><font><font>ضبطه بهذه الطريقة:</font></font></p> + +<pre class="brush:js"><font><font><button onclick = "alert ((function () {return this؛}) ())؛"></font></font><font><font> + أظهر هذا الداخلية</font></font><font><font> +</button></font></font> +</pre> + +<p><font><font>في هذه الحالة ، </font></font><code>this</code><font><font>لم يتم تعيين </font><font>الوظيفة الداخلية ، </font><font>لذا فإنها تُرجع الكائن العام / النافذة (أي الكائن الافتراضي في الوضع غير الصارم حيث </font></font><code>this</code><font><font>لا يتم تعيينه بواسطة المكالمة).</font></font></p> + +<h2 id="مواصفات"><font><font>مواصفات</font></font></h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"><font><font>تخصيص</font></font></th> + </tr> + </thead> + <tbody> + <tr> + <td><font><font>{{SpecName ('ESDraft'، '# sec-this-keyword'، 'The this keyword')}}</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="التوافق_المتصفح"><font><font>التوافق المتصفح</font></font></h2> + +<div class="hidden"><font><font>يتم إنشاء جدول التوافق في هذه الصفحة من البيانات المنظمة. </font><font>إذا كنت ترغب في المساهمة في البيانات ، يرجى مراجعة </font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font> وإرسال طلب سحب إلينا.</font></font></div> + +<p><font><font>{{Compat ("javascript.operators.this")}}</font></font></p> + +<h2 id="أنظر_أيضا"><font><font>أنظر أيضا</font></font></h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode"><font><font>الوضع الصارم</font></font></a></li> + <li><a href="https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/"><font><font>شرح لطيف لكلمة "هذا" في جافا سكريبت</font></font></a></li> + <li><font><font>الحصول على السياق العالمي: {{jsxref ("globalThis")}}</font></font></li> +</ul> 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 +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>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.</p> + +<h2 id="Statements_and_declarations_by_category">Statements and declarations by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Control_flow">Control flow</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>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.</dd> + <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> + <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>Throws a user-defined exception.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> +</dl> + +<h3 id="Declarations">Declarations</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Functions_and_classes">Functions and classes</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>Declares a function with the specified parameters.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd>Generators functions enable writing <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>Specifies the value to be returned by a function.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>Declares a class.</dd> +</dl> + +<h3 id="Iterations">Iterations</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>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.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> + <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> + <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>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.</dd> +</dl> + +<h3 id="Others">Others</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>Used to import functions exported from an external module, another script.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> +</dl> + +<dl> + <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> + <dd>Extends the scope chain for a statement.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: function*, let, for...of, yield, class</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Operators</a></li> +</ul> 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 +--- +<div dir="rtl">{{jsSidebar("Statements")}}</div> + +<p dir="rtl">ال <kbd>return</kbd> ينهي البيان تنفيذ الوظيفة ويحدد قيمة ليتم ارجاعها الى دالة الاستدعاء</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-return.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="بناء_الجملة">بناء الجملة</h2> + +<pre class="syntaxbox notranslate">return [<var>expression</var>]; </pre> + +<dl> + <dt><code><var>expression</var></code></dt> + <dd dir="rtl">التعبير المراد استرجاع قيمتة. اذا تم حذفه, فسيتم ارجاع <kbd>undefined</kbd> بدلاً من ذالك</dd> +</dl> + +<h2 dir="rtl" id="الوصف">الوصف</h2> + +<p dir="rtl">عند استخدام عبارة <kbd>return</kbd> في جسم الدالة,يتم ايقاف تنفيذ الوظيفة.اذا تم تحديد ذالك,يتم ارجاع قيمة معينة الى دالة الاستدعاء.على سبيل المثال,تعرض الدالة التالية مربع سعتها , x,حيث x هي رقم.</p> + +<pre class="brush: js notranslate">function square(x) { + return x * x; +} +var demo = square(3); +// demo will equal 9 +</pre> + +<p dir="rtl">اذا تم حذف القيمة,يتم ارجاع <kbd>undefined</kbd> بدلاُ من ذالك</p> + +<p dir="rtl">تعطل عبارات الارجاع التالية تنفيذ الوظيفة</p> + +<pre class="brush: js notranslate">return; +return true; +return false; +return x; +return x + y / 3; +</pre> + +<h3 dir="rtl" id="الادراج_التلقائي_للفاصلة_المنقوطة_Semicolon">الادراج التلقائي للفاصلة المنقوطة (Semicolon)</h3> + +<p dir="rtl">تتاثر عبارة الارجاع بادراج الفاصلة المنقوطة تلقائياُُ (ASI) .</p> + +<p dir="rtl">لا يُسمح بفاصل سطر بين الكلمة الاساسية <kbd>return</kbd> و التعبير</p> + +<pre class="brush: js notranslate">return +a + b; +</pre> + +<p>is transformed by ASI into:</p> + +<pre class="brush: js notranslate">return; +a + b; +</pre> + +<p>The console will warn "unreachable code after return statement".</p> + +<div class="note">Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a <code>return</code> statement.</div> + +<p>To avoid this problem (to prevent ASI), you could use parentheses:</p> + +<pre class="brush: js notranslate">return ( + a + b +); +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Interrupt_a_function">Interrupt a function</h3> + +<p>A function immediately stops at the point where <code>return</code> is called.</p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 id="Returning_a_function">Returning a function</h3> + +<p>See also the article about <a href="/en-US/docs/Web/JavaScript/Closures">Closures</a>.</p> + +<pre class="brush: js notranslate">function magic() { + return function calc(x) { return x * 42; }; +} + +var answer = magic(); +answer(1337); // 56154 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.return")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Closures">Closures</a></li> +</ul> + +<div id="gtx-trans" style="position: absolute; left: 345px; top: 1247px;"> +<div class="gtx-trans-icon"></div> +</div> diff --git a/files/ar/web/javascript/reference/الدوال/get/index.html b/files/ar/web/javascript/reference/الدوال/get/index.html new file mode 100644 index 0000000000..d3789ba7bd --- /dev/null +++ b/files/ar/web/javascript/reference/الدوال/get/index.html @@ -0,0 +1,165 @@ +--- +title: getter +slug: Web/JavaScript/Reference/الدوال/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>The <strong><code>get</code></strong> صينطاكس طعمنيققbinds an object property to a function that will be called when that property is looked up.</p> + +<div>{{EmbedInteractiveExample("pages/js/functions-getter.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">{get <var>prop</var>() { ... } } +{get [<var>expression</var>]() { ... } }</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>prop</var></code></dt> + <dd>rty to bind to the given fun-tion.</dd> + <dt><code><var>expression</var></code></dt> + <dd>Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>احا الشبشب ضاع احا دا كان ةبصباع</p> + +<p>It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it <em>is</em> possible to use a getter and a setter in conjunction to create a type of pseudo-property.</p> + +<p>Note the following when working with the <code>get</code> syntax:</p> + +<ul> + <li>It can have an identifier which is either a number or a string;</li> + <li>It must have exactly zero parameters (see <a class="external" href="http://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow">Incompatible <abbr title="ECMAScript 5th edition">ES5</abbr> change: literal getter and setter functions must now have exactly zero or one arguments</a> for more information);</li> + <li>It must not appear in an object literal with another <code>get</code> or with a data entry for the same property (<code>{ get x() { }, get x() { } }</code> and <code>{ x: ..., get x() { } }</code> are forbidden).</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<h3 id="Defining_a_getter_on_new_objects_in_object_initializers">Defining a getter on new objects in object initializers</h3> + +<p>This will create a pseudo-property <code>latest</code> for object <code>obj</code>, which will return the last array item in <code>log</code>.</p> + +<pre class="brush: js notranslate">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" +</pre> + +<p>Note that attempting to assign a value to <code>latest</code> will not change it.</p> + +<h3 id="Deleting_a_getter_using_the_delete_operator">Deleting a getter using the <code>delete</code> operator</h3> + +<p>If you want to remove the getter, you can just {{jsxref("Operators/delete", "delete")}} it:</p> + +<pre class="brush: js notranslate">delete <var>obj</var>.latest; +</pre> + +<h3 id="Defining_a_getter_on_existing_objects_using_defineProperty">Defining a getter on existing objects using <code>defineProperty</code></h3> + +<p>To append a getter to an existing object later at any time, use {{jsxref("Object.defineProperty()")}}.</p> + +<pre class="brush: js notranslate">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)</pre> + +<h3 id="Using_a_computed_property_name">Using a computed property name</h3> + +<pre class="brush: js notranslate">const expr = 'foo'; + +const obj = { + get [expr]() { return 'bar'; } +}; + +console.log(obj.foo); // "bar"</pre> + +<h3 id="Smart_self-overwriting_lazy_getters">Smart / self-overwriting / lazy getters</h3> + +<p>Getters give you a way to <em>define</em> a property of an object, but they do not <em>calculate</em> 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.</p> + +<p>An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are <strong>smart (or "<a href="https://en.wikipedia.org/wiki/Memoization">memoized</a>") getters</strong>. 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:</p> + +<ul> + <li>If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker threads, retrieves remote file, etc).</li> + <li>If the value isn't needed just now. It will be used later, or in some case it's not used at all.</li> + <li>If it's used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn't be re-calculated.</li> +</ul> + +<div class="note"> +<p>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.</p> + +<p>Note that getters are not “lazy” or “memozied” by nature; you must implement this technique if you desire this behavior.</p> +</div> + +<p>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'); },</p> + +<p>For Firefox code, see also the <code>XPCOMUtils.jsm</code> code module, which defines the <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter()">defineLazyGetter()</a></code> function.</p> + +<h3 id="get_vs._defineProperty"><code>get</code> vs. <code>defineProperty</code></h3> + +<p>While using the <code>get</code> keyword and {{jsxref("Object.defineProperty()")}} have similar results, there is a subtle difference between the two when used on {{jsxref("classes")}}.</p> + +<p>When using <code>get</code> 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.</p> + +<pre class="brush: js notranslate">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 }</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.functions.get")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li> + <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li> +</ul> diff --git a/files/ar/web/javascript/reference/الدوال/index.html b/files/ar/web/javascript/reference/الدوال/index.html new file mode 100644 index 0000000000..368d8af03d --- /dev/null +++ b/files/ar/web/javascript/reference/الدوال/index.html @@ -0,0 +1,645 @@ +--- +title: الدوال +slug: Web/JavaScript/Reference/الدوال +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> 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 <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Description">Description</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>Functions are not the same as procedures. A function always returns a value, whereas a procedure might not.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is <code>undefined</code>.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. 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:</p> + +<pre class="brush: js">/* 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); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Defining_functions">Defining functions</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> for details):</p> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<div class="note"> +<p><strong>Note:</strong> Generator functions are an <em>experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<div class="note"> +<p><strong>Note:</strong> Generator functions are an <em>experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<p>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):</p> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<div class="note"> +<p><strong>Note:</strong> Arrow function expressions are an <em>experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>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.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Arrow function expressions are an <em>experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Function_parameters">Function parameters</h2> + +<div class="note"> +<p><strong>Note:</strong> Default and rest parameters are <em>experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="The_arguments_object">The <code>arguments</code> object</h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Defining_method_functions">Defining method functions</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>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.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<div class="note"> +<p><strong>Note:</strong> <em>Method definitions are experimental technology,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.</p> +</div> + +<p>Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> constructor assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>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 <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>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.</p> + +<p>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:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>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 <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> 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 "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">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.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">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 + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// 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() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015 (ES6), functions inside blocks are now scoped to that block. Prior to ES6, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> 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 <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (0) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Examples_2">Examples</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// 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; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is peformed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' == typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>39</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>{{CompatUnknown}}</td> + <td>39</td> + <td>{{CompatGeckoMobile("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope" title="JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> |