From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../reference/global_objects/array/index.html | 481 +++++++++++++++++++++ .../global_objects/array/isarray/index.html | 146 +++++++ .../reference/global_objects/array/join/index.html | 143 ++++++ .../reference/global_objects/array/pop/index.html | 134 ++++++ .../global_objects/array/reverse/index.html | 124 ++++++ .../global_objects/array/slice/index.html | 151 +++++++ .../global_objects/date/getdate/index.html | 85 ++++ .../reference/global_objects/date/index.html | 261 +++++++++++ .../reference/global_objects/date/now/index.html | 80 ++++ .../reference/global_objects/date/parse/index.html | 182 ++++++++ .../global_objects/date/setdate/index.html | 95 ++++ .../reference/global_objects/date/utc/index.html | 133 ++++++ .../global_objects/function/call/index.html | 219 ++++++++++ .../reference/global_objects/function/index.html | 183 ++++++++ .../javascript/reference/global_objects/index.html | 126 ++++++ .../reference/global_objects/json/index.html | 215 +++++++++ .../reference/global_objects/map/index.html | 358 +++++++++++++++ .../reference/global_objects/math/index.html | 190 ++++++++ .../global_objects/object/constructor/index.html | 152 +++++++ .../reference/global_objects/object/index.html | 182 ++++++++ .../reference/global_objects/string/index.html | 314 ++++++++++++++ .../global_objects/string/startswith/index.html | 101 +++++ .../index.html" | 12 + 23 files changed, 4067 insertions(+) create mode 100644 files/ar/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/map/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/math/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 "files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" (limited to 'files/ar/web/javascript/reference/global_objects') diff --git a/files/ar/web/javascript/reference/global_objects/array/index.html b/files/ar/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..1e00adcf73 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,481 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +
كائن Array في جافاسكربت  هو كائن عام، يستخدم في إنشاء المصفوفات، وهي تشبه قائمة من الكائنات عالية المستوى.
+ +
 
+ +

إنشاء مصفوفة

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

نسخة مصفوفة

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

Syntax

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

Parameters

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

الوصف

+ +

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

+ +

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

+ +

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

+ +

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

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

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

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

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

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

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

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

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

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

Relationship between length and numerical properties

+ +

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

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

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

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

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

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

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

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

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

+ +

Creating an array using the result of a match

+ +

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

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

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

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

الخصائص

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

الدوال

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

Array instances

+ +

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

+ +

الخصائص

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

الدوال

+ +

Mutator methods

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

Accessor methods

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

Iteration methods

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

Array generic methods

+ +
+

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

+
+ +

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

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

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

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

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

+ +

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

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

أمثلة

+ +

إنشاء مصفوفة

+ +

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

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

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

+ +

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

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

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

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

Specifications

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

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

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

إقرأ أيضا

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

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

+ +

بنية الجملة

+ +
Array.isArray(value)
+ +

المعلمات

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

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

+ +

أمثلة

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

Polyfill

+ +

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

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

المواصفات

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

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

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

إقرأ أيضا

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

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

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

صيغة الكتابة

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

المعاملات

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

أمثلة

+ +

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

+ +

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

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

المواصفات

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

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

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

إقرأ أيضا

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

Syntax

+ +
arr.pop()
+ +

قيمة الإرجاع

+ +

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

+ +

وصف

+ +

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

+ +

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

+ +

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

+ +

أمثلة

+ +

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

+ +

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

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

مواصفات

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

Browser compatibility

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

See also

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

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

+ +

صيغة الكتابة

+ +
arr.reverse()
+ +

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

+ +

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

+ +

الوصف

+ +

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

+ +

أمثلة

+ +

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

+ +

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

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

المواصفات

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

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

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

إقرأ أيضا

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

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

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

تركيب الجملة

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

المعاملات

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

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

+ +

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

+ +

الوصف

+ +

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

+ + + +

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

+ +

أمثلة

+ +

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

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

باستخدام slice

+ +

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

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

This script writes:

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

Array-like objects

+ +

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

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

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

+ +

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

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

المواصفات

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

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

+ + + +

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

+ +

انظر أيضا

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

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

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

بنية الجملة

+ +
dateObj.getDate()
+
+ +

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

+ +

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

+ +

أمثلة

+ +

استخدام getDate()

+ +

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

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

الخصائص

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

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

+ + + +

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

+ +

اقرأ أيضًا

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

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

+ +

البنيه

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

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

+
+ +

Parameters

+ +
+

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

+
+ +
+

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

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

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

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

Description

+ + + +

Properties

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

Methods

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

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

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

JavaScript Date instances

+ +

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

+ +

Date.prototype Methods

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

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

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

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

Two digit years map to 1900 - 1999

+ +

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

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

Calculating elapsed time

+ +

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

+ +

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

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

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

+
+ +

Specifications

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

Browser compatibility

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

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

+ +

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

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

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

+ +

بنية الجملة

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

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

+ +

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

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

الخصائص

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

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

+ + + +

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

+ +

اقرأ أيضًا

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

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

+ +

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

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

بنية الجملة

+ +

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

+ +
Date.parse(dateString)
+ +

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

+ +
new Date(dateString)
+ +

المعاملات

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Fall-back to implementation-specific date formats

+ +

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

+ +

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

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

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

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

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

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

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

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

أمثلة

+ +

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

+ +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ +

الخصائص

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

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

+ + + +

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

+ +

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

+ + + +

اقرأ أيضًا

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

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

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

بنية الجملة

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

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

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

أمثلة

+ +

استخدام setDate()

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

الخصائص

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

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

+ + + +

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

+ +

اقرأ أيضًا

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

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

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

بنية الجملة

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

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

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

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

+ +

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

+ +

الوصف

+ +

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

أمثلة

+ +

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

+ +

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

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

الخصائص

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

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

+ + + +

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

+ +

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

+ +

Date.UTC with fewer than two arguments

+ +

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

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

اقرأ أيضاً

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

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

+ +
+

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

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

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

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

Parameters

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

Return value

+ +

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

+ +

وصف

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

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

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

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

+ +

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

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

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

+ +
+

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

+
+ +

أمثلة

+ +

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

+ +

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

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

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

+ +

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

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

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

+ +

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

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

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

+ +

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

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

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

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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

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

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

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

+ +

Syntax

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

Parameters

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

Description

+ +

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

+ +

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

+ +

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

+ +

Properties and Methods of Function

+ +

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

+ +

Function prototype object

+ +

Properties

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

Methods

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

Function instances

+ +

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

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

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

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

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

+ +

Difference between Function constructor and function declaration

+ +

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

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

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

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

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

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

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

Summary

+

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

+
+

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

+

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

+

Standard objects (by category)

+

Value properties

+

Global properties returning a simple value.

+ +

Function properties

+

Global functions returning the result of a specific routine.

+ +

Fundamental objects

+

General language objects, functions and errors.

+ +

Numbers and dates

+

Objects dealing with numbers, dates and mathematical calculations.

+ +

Text processing

+

Objects for manipulating texts.

+ +

Indexed collections

+

Collections ordered by an index. Array-type objects.

+ +

Keyed collections

+

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

+ +

Structured data

+

Data buffers and JavaScript Object Notation.

+ +

Control abstraction objects

+ +

Reflection

+ +

Internationalization

+

Additions to the ECMAScript core for language-sensitive functionalities.

+ +

Other

+ +
+

 

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

Summary

+

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

+ +

Description

+ +

JavaScript Object Notation

+

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

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

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

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

The full JSON syntax is as follows:

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

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

+ +

Methods

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

Polyfill

+

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

+

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

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

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

+ +

Specifications

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

Browser compatibility

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

Based on Kangax's compat table.

+ +

See also

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

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

+ +

Description

+ +

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

+ +

Key equality

+ + + +

Objects vs. Maps

+ +

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

+ +

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

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

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

+ +
+

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

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

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

+
+

The keys of an Object are not ordered.

+ +
+

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

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

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

+
+

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

+
+ +

Setting object properties

+ +

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

+ +

Therefore, this appears to work in a way:

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

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

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

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

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

Constructor

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

Static properties

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

Instance properties

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

Instance methods

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

Examples

+ +

Using the Map object

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

Using NaN as Map keys

+ +

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

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

Iterating Map with for..of

+ +

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

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

Iterating Map with forEach()

+ +

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

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

Relation with Array objects

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

Cloning and merging Maps

+ +

Just like Arrays, Maps can be cloned:

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

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

+
+ +

Maps can be merged, maintaining key uniqueness:

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

Maps can be merged with Arrays, too:

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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

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

+ +

Description

+ +

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

+ +

Properties

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

Methods

+ +
+

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

+
+ +
+

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

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

Extending the Math object

+ +

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

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

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

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

Try it:

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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

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

+ +

الوصف

+ +

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

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

أمثلة

+ +

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

+ +

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

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

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

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

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

+ +

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

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

This example displays the following output:

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

Specifications

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

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

+ +
+ + +

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

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

The Object constructor creates an object wrapper.

+ +

Syntax

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

Parameters

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

Description

+ +

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

+ +

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

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

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

Methods of the Object constructor

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

Object instances and Object prototype object

+ +

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

+ +

Properties

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

Methods

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

Deleting a property from an object

+ +

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

+ +

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

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

Using Object to create Boolean objects

+ +

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

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

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

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

+ +

Syntax

+ +

String literals take the forms:

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

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

+ +
String(thing)
+ +

Parameters

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

Template literals

+ +

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

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

Escape notation

+ +

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

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

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

+
+ +
+
+ +

Long literal strings

+ +

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

+ +

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

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

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

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

Both of these result in identical strings being created.

+ +

Description

+ +

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

+ +

Character access

+ +

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

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

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

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

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

+ +

Comparing strings

+ +

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

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

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

+ +

Distinction between string primitives and String objects

+ +

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

+ +

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

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

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

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

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

+ +

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

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

Properties

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

Methods

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

String generic methods

+ +
+

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

+
+ +

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

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

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

+ +

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

+ +

String instances

+ +

Properties

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

Methods

+ +

Methods unrelated to HTML

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

HTML wrapper methods

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

Examples

+ +

String conversion

+ +

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

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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

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

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

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

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

المعاملات | Parameters

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

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

+ +

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

+ +

الوصف | Description

+ +

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

+ +

أمثلة | Examples

+ +

Using startsWith()

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

Polyfill

+ +

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

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

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

+ +

Specifications

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

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

+ + + +

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

+ +

ذات صلة

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

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

+ +

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

+ +

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

+ +

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

-- cgit v1.2.3-54-g00ecf