From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../he/web/javascript/reference/errors/index.html | 31 ++ .../functions/default_parameters/index.html | 216 ++++++++ .../web/javascript/reference/functions/index.html | 596 +++++++++++++++++++++ .../reference/global_objects/array/from/index.html | 243 +++++++++ .../global_objects/array/includes/index.html | 169 ++++++ .../reference/global_objects/array/index.html | 485 +++++++++++++++++ .../global_objects/array/unshift/index.html | 94 ++++ .../javascript/reference/global_objects/index.html | 183 +++++++ .../global_objects/object/assign/index.html | 272 ++++++++++ .../reference/global_objects/object/index.html | 184 +++++++ .../reference/global_objects/promise/index.html | 244 +++++++++ .../reference/global_objects/string/index.html | 314 +++++++++++ files/he/web/javascript/reference/index.html | 58 ++ .../operators/destructuring_assignment/index.html | 416 ++++++++++++++ .../web/javascript/reference/operators/index.html | 289 ++++++++++ .../operators/operator_precedence/index.html | 330 ++++++++++++ .../reference/statements/const/index.html | 133 +++++ .../reference/statements/for...of/index.html | 269 ++++++++++ .../reference/statements/for_each...in/index.html | 128 +++++ .../reference/statements/function_star_/index.html | 212 ++++++++ .../web/javascript/reference/statements/index.html | 148 +++++ .../reference/statements/return/index.html | 151 ++++++ .../javascript/reference/statements/var/index.html | 171 ++++++ 23 files changed, 5336 insertions(+) create mode 100644 files/he/web/javascript/reference/errors/index.html create mode 100644 files/he/web/javascript/reference/functions/default_parameters/index.html create mode 100644 files/he/web/javascript/reference/functions/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/he/web/javascript/reference/global_objects/index.html create mode 100644 files/he/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/he/web/javascript/reference/global_objects/object/index.html create mode 100644 files/he/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/he/web/javascript/reference/global_objects/string/index.html create mode 100644 files/he/web/javascript/reference/index.html create mode 100644 files/he/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/he/web/javascript/reference/operators/index.html create mode 100644 files/he/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/he/web/javascript/reference/statements/const/index.html create mode 100644 files/he/web/javascript/reference/statements/for...of/index.html create mode 100644 files/he/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/he/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/he/web/javascript/reference/statements/index.html create mode 100644 files/he/web/javascript/reference/statements/return/index.html create mode 100644 files/he/web/javascript/reference/statements/var/index.html (limited to 'files/he/web/javascript/reference') diff --git a/files/he/web/javascript/reference/errors/index.html b/files/he/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/he/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

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

+ +

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

+ +

List of errors

+ +

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

+ +

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

+ +

See also

+ + diff --git a/files/he/web/javascript/reference/functions/default_parameters/index.html b/files/he/web/javascript/reference/functions/default_parameters/index.html new file mode 100644 index 0000000000..2d4215bcad --- /dev/null +++ b/files/he/web/javascript/reference/functions/default_parameters/index.html @@ -0,0 +1,216 @@ +--- +title: Default parameters +slug: Web/JavaScript/Reference/Functions/Default_parameters +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +
{{jsSidebar("Functions")}}
+ +
הצבת פרמטר ברירת מחדל לפונקציה מאפשר רישום של ערך ראשוני בזמן הגדרת הפונקציה, כך שאם לא מועבר ערך בקריאה (הפעלה) של הפונקציה, או שמעבירים undefined כערך, הערך הראשוני שהוגדר כברירת מחדל ישמש בתור הפרמטר של הפונקציה.
+ +

 

+ +

שימוש בשפה

+ +
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
+   statements
+}
+
+ +

תיאור שימושיות

+ +

הערך ראשוני של פרמטר בפונקציה ב JavaScript שווה ל undefined. אומנם ישנם מקרים בהם זה יכול להיות נוח להציב ערך שונה כערך ראשוני לפרמטר של הפונקציה, כך שהערך יוגדר מראש ביצירת הפונקציה. ופה אנחנו נעזרים בהצבת פרמטר ברירת מחדל לפונקציה.

+ +

האסטרטגיה הכללית שהשתמשו בה לפני פרמטר ברירת המחדל, היתה בדיקה שנכללה בתוך גוף הפונקציה ובדקה אם הפרמטר מכיל ערך או שהוא אינו מוגדר, ולא נעשה בו שימוש בקריאה לפונקציה. בדוגמא שלפנינו אם לא נעביר ערך ל b בקריאה לפונקציה (בהפעלה שלה, בכל  הפעלה לש פונקציה אנחנו קוראים לה מהזיכרון), היא תקבל ערך לא מוגדר (undefined) וכאשר תיקראו לפונקציה multiply כדי לחשב את a*b התוצאה תהיה NaN. לשם כך השורה השניה בפונקציה בודקת אם קיים בפרמטר b ערך השונה מ undefined ואם לא נעשה שימוש בפרמטר b בקריאה לפונקציה אז מציבים בו ערך ראשוני של 1:

+ +
function multiply(a, b) {
+  b = (typeof b !== 'undefined') ?  b : 1;
+  return a * b;
+}
+
+multiply(5, 2); // 10
+multiply(5, 1); // 5
+multiply(5);    // 5
+
+ +

בעזרת הצבה של פרמטר ברירת מחדל לפונקציה הניתן לשימוש מגרסה ES2015 הבדיקה בגוף הפונקציה כבר לא נחוצה. עכשיו אפשר פשוט להציב ערך ראשוני כערך ברירת מחדל בהגדרה של הפונקציה והפרמטרים שלה:

+ +
function multiply(a, b = 1) {
+  return a * b;
+}
+
+multiply(5, 2); // 10
+multiply(5, 1); // 5
+multiply(5);    // 5
+
+ +

דוגמאות

+ +

קריאה לפונקציה עם ערך של undefined מול ערכים שליליים שונים.

+ +

בהפעלה השניה של הפונקציה בדוגמה test אנחנו מעבירים באופן מכוון ערך של undefined והפרמטר num עדיין מקבל את ערך ברירת המחדל שהגדרנו בעת יצירת הפונקציה (num = 1). ניתן לראות בקריאות הבאות לפונקציה, כי אך ורק undefined זוכה להחלפה בערך ברירת המחדל ולא שום סוג של ערך שלילי אחר ( num === fale!! ).

+ +
function test(num = 1) {
+  console.log(typeof num);
+}
+
+test();          // 'number' (num is set to 1)
+test(undefined); // 'number' (num is set to 1 too)
+
+// test with other falsy values:
+test('');        // 'string' (num is set to '')
+test(null);      // 'object' (num is set to null)
+
+ +

Evaluated at call time

+ +

The default argument gets evaluated at call time, so unlike e.g. in Python, a new object is created each time the function is called.

+ +
function append(value, array = []) {
+  array.push(value);
+  return array;
+}
+
+append(1); //[1]
+append(2); //[2], not [1, 2]
+
+
+ +

This even applies to functions and variables:

+ +
function callSomething(thing = something()) {
+ return thing;
+}
+
+function something() {
+  return 'sth';
+}
+
+callSomething();  //sth
+ +

Default parameters are available to later default parameters

+ +

Parameters already encountered are available to later default parameters:

+ +
function singularAutoPlural(singular, plural = singular + 's',
+                            rallyingCry = plural + ' ATTACK!!!') {
+  return [singular, plural, rallyingCry];
+}
+
+//["Gecko","Geckos", "Geckos ATTACK!!!"]
+singularAutoPlural('Gecko');
+
+//["Fox","Foxes", "Foxes ATTACK!!!"]
+singularAutoPlural('Fox', 'Foxes');
+
+//["Deer", "Deer", "Deer ... change."]
+singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \
+   petition the government for positive change.')
+
+ +

This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.

+ +
function go() {
+  return ':P';
+}
+
+function withDefaults(a, b = 5, c = b, d = go(), e = this,
+                      f = arguments, g = this.value) {
+  return [a, b, c, d, e, f, g];
+}
+
+function withoutDefaults(a, b, c, d, e, f, g) {
+  switch (arguments.length) {
+    case 0:
+      a;
+    case 1:
+      b = 5;
+    case 2:
+      c = b;
+    case 3:
+      d = go();
+    case 4:
+      e = this;
+    case 5:
+      f = arguments;
+    case 6:
+      g = this.value;
+    default:
+  }
+  return [a, b, c, d, e, f, g];
+}
+
+withDefaults.call({value: '=^_^='});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+
+withoutDefaults.call({value: '=^_^='});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+ +

Functions defined inside function body

+ +

Introduced in Gecko 33 {{geckoRelease(33)}}. Functions declared in the function body cannot be referred inside default parameters and throw a {{jsxref("ReferenceError")}} (currently a {{jsxref("TypeError")}} in SpiderMonkey, see {{bug(1022967)}}). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.

+ +
// Doesn't work! Throws ReferenceError.
+function f(a = go()) {
+  function go() { return ':P'; }
+}
+
+ +

Parameters without defaults after default parameters

+ +

Prior to Gecko 26 {{geckoRelease(26)}}, the following code resulted in a {{jsxref("SyntaxError")}}. This has been fixed in {{bug(777060)}} and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

+ +
function f(x = 1, y) {
+  return [x, y];
+}
+
+f(); // [1, undefined]
+f(2); // [2, undefined]
+
+ +

Destructured parameter with default value assignment

+ +

You can use default value assignment with the destructuring assignment notation:

+ +
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
+  return x + y + z;
+}
+
+f(); // 6
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.functions.default_parameters")}}

+
+ +

See also

+ + diff --git a/files/he/web/javascript/reference/functions/index.html b/files/he/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..a58e629441 --- /dev/null +++ b/files/he/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Declare variable 'mycar';
+  * create and initialize a new Object;
+  * assign reference to it to 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Pass object reference to the function */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' as the value of the 'brand' property
+  * of the object, as changed to by the function.
+  */
+ console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

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

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Function constructor vs. function declaration vs. function expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x === 0) {           // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y === 10) {    // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/he/web/javascript/reference/global_objects/array/from/index.html b/files/he/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..1ab52ffa12 --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,243 @@ +--- +title: ()Array.from +slug: Web/JavaScript/Reference/Global_Objects/Array/from +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
מתודת ה-
+ +
Array.from() 
+ +
יוצרת מערך חדש שהוא העתק בעומק אחד (לא יכלול את האובייקטים אליהם יש הפניות מאיברים במערך הנתון) של המערך או אובייקט איטרבילי המועבר כפרמטר.
+ +
+ +
{{EmbedInteractiveExample("pages/js/array-from.html")}}
+ + + +

Syntax

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

Parameters

+ +
+
arrayLike
+
An array-like or iterable object to convert to an array.
+
mapFn {{Optional_inline}}
+
Map function to call on every element of the array.
+
thisArg {{Optional_inline}}
+
Value to use as this when executing mapFn.
+
+ +

Return value

+ +

A new {{jsxref("Array")}} instance.

+ +

Description

+ +

Array.from() lets you create Arrays from:

+ + + +

Array.from() has an optional parameter mapFn, which allows you to execute a {{jsxref("Array.prototype.map", "map")}} function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

+ +

The length property of the from() method is 1.

+ +

In ES2015, the class syntax allows for sub-classing of both built-in and user defined classes; as a result, static methods such as Array.from are "inherited" by subclasses of Array and create new instances of the subclass, not Array.

+ +

Examples

+ +

Array from a String

+ +
Array.from('foo');
+// [ "f", "o", "o" ]
+ +

Array from a Set

+ +
const set = new Set(['foo', 'bar', 'baz', 'foo']);
+Array.from(set);
+// [ "foo", "bar", "baz" ]
+ +

Array from a Map

+ +
const map = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(map);
+// [[1, 2], [2, 4], [4, 8]]
+
+const mapper = new Map([['1', 'a'], ['2', 'b']]);
+Array.from(mapper.values());
+// ['a', 'b'];
+
+Array.from(mapper.keys());
+// ['1', '2'];
+
+ +

Array from an Array-like object (arguments)

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [ 1, 2, 3 ]
+ +

Using arrow functions and Array.from

+ +
// Using an arrow function as the map function to
+// manipulate the elements
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+
+// Generate a sequence of numbers
+// Since the array is initialized with `undefined` on each position,
+// the value of `v` below will be `undefined`
+Array.from({length: 5}, (v, i) => i);
+// [0, 1, 2, 3, 4]
+
+ +

Sequence generator (range)

+ +
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
+const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
+
+// Generate numbers range 0..4
+range(0, 4, 1);
+// [0, 1, 2, 3, 4]
+
+// Generate numbers range 1..10 with step of 2
+range(1, 10, 2);
+// [1, 3, 5, 7, 9]
+
+// Generate the alphabet using Array.from making use of it being ordered as a sequence
+range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
+// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
+
+ +

Polyfill

+ +

Array.from was added to the ECMA-262 standard in the 6th edition (ES2015); as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of Array.from in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 6th edition, assuming Object and TypeError have their original values and that callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}. In addition, since true iterables can not be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ECMA-262.

+ +
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+if (!Array.from) {
+  Array.from = (function () {
+    var toStr = Object.prototype.toString;
+    var isCallable = function (fn) {
+      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
+    };
+    var toInteger = function (value) {
+      var number = Number(value);
+      if (isNaN(number)) { return 0; }
+      if (number === 0 || !isFinite(number)) { return number; }
+      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
+    };
+    var maxSafeInteger = Math.pow(2, 53) - 1;
+    var toLength = function (value) {
+      var len = toInteger(value);
+      return Math.min(Math.max(len, 0), maxSafeInteger);
+    };
+
+    // The length property of the from method is 1.
+    return function from(arrayLike/*, mapFn, thisArg */) {
+      // 1. Let C be the this value.
+      var C = this;
+
+      // 2. Let items be ToObject(arrayLike).
+      var items = Object(arrayLike);
+
+      // 3. ReturnIfAbrupt(items).
+      if (arrayLike == null) {
+        throw new TypeError('Array.from requires an array-like object - not null or undefined');
+      }
+
+      // 4. If mapfn is undefined, then let mapping be false.
+      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
+      var T;
+      if (typeof mapFn !== 'undefined') {
+        // 5. else
+        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
+        if (!isCallable(mapFn)) {
+          throw new TypeError('Array.from: when provided, the second argument must be a function');
+        }
+
+        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
+        if (arguments.length > 2) {
+          T = arguments[2];
+        }
+      }
+
+      // 10. Let lenValue be Get(items, "length").
+      // 11. Let len be ToLength(lenValue).
+      var len = toLength(items.length);
+
+      // 13. If IsConstructor(C) is true, then
+      // 13. a. Let A be the result of calling the [[Construct]] internal method
+      // of C with an argument list containing the single item len.
+      // 14. a. Else, Let A be ArrayCreate(len).
+      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
+
+      // 16. Let k be 0.
+      var k = 0;
+      // 17. Repeat, while k < len… (also steps a - h)
+      var kValue;
+      while (k < len) {
+        kValue = items[k];
+        if (mapFn) {
+          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
+        } else {
+          A[k] = kValue;
+        }
+        k += 1;
+      }
+      // 18. Let putStatus be Put(A, "length", len, true).
+      A.length = len;
+      // 20. Return A.
+      return A;
+    };
+  }());
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/he/web/javascript/reference/global_objects/array/includes/index.html b/files/he/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..0cc6181f0d --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,169 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - ג'אווה סקריפט + - מערך + - פוליפיל + - פרוטוטייפ +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +
שיטת includes() קובעת אם מערך מכיל אלמנט מסויים, מחזיר true או false בהתאם.
+ +
 
+ +

תחביר

+ +
var boolean = array.includes(searchElement[, fromIndex])
+ +

פרמטרים

+ +
+
searchElement
+
האלמנט אותו מחפשים
+
fromIndex
+
אופציונלי. המיקום במערך בו להתחיל את החיפוש אחר searchElement. ערך שלילי יתחיל את החיפוש מהערך האחרון (array.length) + fromIndex בסדר עולה. ברירת מחדל 0.
+
+ +

ערך מוחזר (Return)

+ +

{{jsxref("Boolean")}}.

+ +

דוגמאות

+ +
[1, 2, 3].includes(2);     // true
+[1, 2, 3].includes(4);     // false
+[1, 2, 3].includes(3, 3);  // false
+[1, 2, 3].includes(3, -1); // true
+[1, 2, NaN].includes(NaN); // true
+
+ +

פוליפיל - Polyfill

+ +
if (!Array.prototype.includes) {
+  Array.prototype.includes = function(searchElement /*, fromIndex*/) {
+    'use strict';
+    if (this == null) {
+      throw new TypeError('Array.prototype.includes called on null or undefined');
+    }
+
+    var O = Object(this);
+    var len = parseInt(O.length, 10) || 0;
+    if (len === 0) {
+      return false;
+    }
+    var n = parseInt(arguments[1], 10) || 0;
+    var k;
+    if (n >= 0) {
+      k = n;
+    } else {
+      k = len + n;
+      if (k < 0) {k = 0;}
+    }
+    var currentElement;
+    while (k < len) {
+      currentElement = O[k];
+      if (searchElement === currentElement ||
+         (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
+        return true;
+      }
+      k++;
+    }
+    return false;
+  };
+}
+
+ +

מפרט

+ + + + + + + + + + + + + + + + + + + +
  מפרטסטטוסהערה
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}הגדרה ראשונית
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

תאימות דפדפנים

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
מאפייןChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
תמיכה בסיסית +

{{CompatChrome(47)}}

+
43{{CompatNo}}14279+349
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
מאפייןAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
תמיכה בסיסית{{CompatNo}} +

{{CompatChrome(47)}}

+
43{{CompatNo}}349 +

{{CompatChrome(47)}}

+
+
+ +

ראה עוד

+ + diff --git a/files/he/web/javascript/reference/global_objects/array/index.html b/files/he/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..4dac733b4a --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,485 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - דוגמא + - מערך +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +

האובייקט מערך(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"]
+
+ +

תחביר

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

פרמטרים

+ +
+
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.
+
+ +

Description

+ +

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 מסודרים לפי מספרים מאפס ומעלה: מספרו של האיבר הראשון במערך הוא 0 ומספרו של האיבר האחרון במערך שווה לכמות האיברים במערך (אורכו של המערך - Array.length) פחות 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
+ +

Properties

+ +
+
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.
+
+ +

Methods

+ +
+
{{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.

+ +

Properties

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

Methods

+ +

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 ES2015 {{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]);
+  }
+}());
+
+ +

דוגמאות

+ +

Creating an array

+ +

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.');
+}
+
+ +

Creating a two-dimensional array

+ +

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'));
+
+ +

Here is the output:

+ +
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('ES2015', '#sec-array-objects', 'Array')}}{{Spec2('ES2015')}}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()")}}
+ +

Browser compatibility

+ +
{{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/he/web/javascript/reference/global_objects/array/unshift/index.html b/files/he/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..9febfb5ad4 --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,94 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +
המתודה ()unshift  מוסיפה אלמנט אחד או יותר לתחילת מערך ומחזירה את גודלו החדש של המערך. 
+ +
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
+ +

Syntax

+ +
arr.unshift(element1[, ...[, elementN]])
+ +

פרמטרים

+ +
+
elementN
+
אלמנטים להוספה לתחילת המערך.
+
+ +

ערך מוחזר

+ +

את ערך השדה {{jsxref("Array.length", "length")}} החדש של המערך עליו הופעלה המתודה.

+ +

תאור

+ +

המתודה unshift מכניסה את ערכי האלמנטים שקיבלה כפרמטר לתחילת אובייקט המערך. 

+ +

unshift 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.

+ +

Examples

+ +
var arr = [1, 2];
+
+arr.unshift(0); // result of call is 3, the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/he/web/javascript/reference/global_objects/index.html b/files/he/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..f215b83a20 --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/index.html @@ -0,0 +1,183 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Objects + - אובייקטים + - סקריפט + - פונקציות +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

This chapter documents all of JavaScript's standard, built-in objects, including 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; in that case it returns {{jsxref("undefined")}}). The global object itself can be accessed using 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

+ +

These global properties return a simple value; they have no properties or methods.

+ + + +

Function properties

+ +

These global functions—functions which are called globally rather than on an object—directly return their results to the caller.

+ + + +

Fundamental objects

+ +

These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.

+ + + +

Numbers and dates

+ +

These are the base objects representing numbers, dates, and mathematical calculations.

+ + + +

Text processing

+ +

These objects represent strings and support manipulating them.

+ + + +

Indexed collections

+ +

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

+ + + +

Keyed collections

+ +

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

+ + + +

Vector collections

+ +

{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.

+ + + +

Structured data

+ +

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

+ + + +

Control abstraction objects

+ + + +

Reflection

+ + + +

Internationalization

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

Non-standard objects

+ + + +

Other

+ + +
+ +

 

diff --git a/files/he/web/javascript/reference/global_objects/object/assign/index.html b/files/he/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..72d2b16579 --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,272 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +

{{JSRef}}

+ +

מתודת Object.assign מעתיקה אובייקט על שלל {{jsxref("Object/propertyIsEnumerable", "מאפייניו", "", 1)} {{jsxref("Object/hasOwnProperty", "הקיימים", "", 1)}} לאובייקט אחר וממזגת אותם ביחד. המתודה מחזירה את האובייקט שאליו העתקנו את התכונות החדשות. 

+ +
תחביר
+ +
Object.assign(target, ...sources)
+ +

פרמטרים

+ +
+
target - אובייקט היעד
+
אובייקט היעד- האובייקט שאליו אנחנו מעתיקים את כל המאפיינים של האובייקט המקורי, כאשר הוא מחזיר את האובייקט אחרי המיזוג.
+
sources - אובייקט המקור
+
+
+ +
+
אובייקט המקור - האובייקט מכיל את המאפיינים שאנחנו רוצים להעתיק לאובייקט נוסף. 
+
+ +

Return value - הנתון התוצאה

+ +

The target object - האובייקט שאליו העתקנו את התכונות של האובייקט המקורי.

+ +

תיאור

+ +

מאפיינים באובייקט היעד ישוכתבו או ידרסו ע"י המאפיינים של אובייקט המקור אם הם חולקים את אותו ה-{{jsxref("Object/keys", "key", "", 1)}}. מאפיינים חדשים שיוגדו על מאפיינים משותפים (properties) בהמשך ידרסו גם באובייקט היעד וגם באופייקט המקור.

+ +

+ +

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

+ +

For copying property definitions (including their enumerability) into prototypes, use {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.defineProperty()")}} instead.

+ +

Both {{jsxref("String")}} and {{jsxref("Symbol")}} properties are copied.

+ +

In case of an error, for example if a property is non-writable, a {{jsxref("TypeError")}} is raised, and the target object is changed if any properties are added before the error is raised.

+ +
+

Note: Object.assign() does not throw on {{jsxref("null")}} or {{jsxref("undefined")}} sources.

+
+ +

Polyfill

+ +

This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway:

+ +
if (typeof Object.assign !== 'function') {
+  // Must be writable: true, enumerable: false, configurable: true
+  Object.defineProperty(Object, "assign", {
+    value: function assign(target, varArgs) { // .length of function is 2
+      'use strict';
+      if (target === null || target === undefined) {
+        throw new TypeError('Cannot convert undefined or null to object');
+      }
+
+      var to = Object(target);
+
+      for (var index = 1; index < arguments.length; index++) {
+        var nextSource = arguments[index];
+
+        if (nextSource !== null && nextSource !== undefined) {
+          for (var nextKey in nextSource) {
+            // Avoid bugs when hasOwnProperty is shadowed
+            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
+              to[nextKey] = nextSource[nextKey];
+            }
+          }
+        }
+      }
+      return to;
+    },
+    writable: true,
+    configurable: true
+  });
+}
+
+ +

Examples

+ +

Cloning an object

+ +
const obj = { a: 1 };
+const copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

Warning for Deep Clone

+ +

For deep cloning, we need to use alternatives, because Object.assign() copies property values.

+ +

If the source value is a reference to an object, it only copies the reference value.

+ +
function test() {
+  'use strict';
+
+  let obj1 = { a: 0 , b: { c: 0}};
+  let obj2 = Object.assign({}, obj1);
+  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
+
+  obj1.a = 1;
+  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
+  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}
+
+  obj2.a = 2;
+  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
+  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
+
+  obj2.b.c = 3;
+  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
+  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}
+
+  // Deep Clone
+  obj1 = { a: 0 , b: { c: 0}};
+  let obj3 = JSON.parse(JSON.stringify(obj1));
+  obj1.a = 4;
+  obj1.b.c = 4;
+  console.log(JSON.stringify(obj3)); // { "a": 0, "b": { "c": 0}}
+}
+
+test();
+ +

Merging objects

+ +
const o1 = { a: 1 };
+const o2 = { b: 2 };
+const o3 = { c: 3 };
+
+const obj = Object.assign(o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.
+ +

Merging objects with same properties

+ +
const o1 = { a: 1, b: 1, c: 1 };
+const o2 = { b: 2, c: 2 };
+const o3 = { c: 3 };
+
+const obj = Object.assign({}, o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+ +

The properties are overwritten by other objects that have the same properties later in the parameters order.

+ +

Copying symbol-typed properties

+ +
const o1 = { a: 1 };
+const o2 = { [Symbol('foo')]: 2 };
+
+const obj = Object.assign({}, o1, o2);
+console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
+Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
+
+ +

Properties on the prototype chain and non-enumerable properties cannot be copied

+ +
const obj = Object.create({ foo: 1 }, { // foo is on obj's prototype chain.
+  bar: {
+    value: 2  // bar is a non-enumerable property.
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz is an own enumerable property.
+  }
+});
+
+const copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+
+ +

Primitives will be wrapped to objects

+ +
const v1 = 'abc';
+const v2 = true;
+const v3 = 10;
+const v4 = Symbol('foo');
+
+const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// Primitives will be wrapped, null and undefined will be ignored.
+// Note, only string wrappers can have own enumerable properties.
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+
+ +

Exceptions will interrupt the ongoing copying task

+ +
const target = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writable: false
+}); // target.foo is a read-only property
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" is read-only
+// The Exception is thrown when assigning target.foo
+
+console.log(target.bar);  // 2, the first source was copied successfully.
+console.log(target.foo2); // 3, the first property of the second source was copied successfully.
+console.log(target.foo);  // 1, exception is thrown here.
+console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
+console.log(target.baz);  // undefined, the third source will not be copied either.
+
+ +

Copying accessors

+ +
const obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+let copy = Object.assign({}, obj);
+console.log(copy);
+// { foo: 1, bar: 2 }
+// The value of copy.bar is obj.bar's getter's return value.
+
+// This is an assign function that copies full descriptors
+function completeAssign(target, ...sources) {
+  sources.forEach(source => {
+    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {});
+
+    // By default, Object.assign copies enumerable Symbols, too
+    Object.getOwnPropertySymbols(source).forEach(sym => {
+      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+      if (descriptor.enumerable) {
+        descriptors[sym] = descriptor;
+      }
+    });
+    Object.defineProperties(target, descriptors);
+  });
+  return target;
+}
+
+copy = completeAssign({}, obj);
+console.log(copy);
+// { foo:1, get bar() { return 2 } }
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/he/web/javascript/reference/global_objects/object/index.html b/files/he/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..9feed92ddc --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,184 @@ +--- +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.fromEntries()")}}
+
Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).
+
{{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/he/web/javascript/reference/global_objects/promise/index.html b/files/he/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..1f1c71827c --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,244 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

+ +
+

Note: This article describes the Promise constructor and the methods and properties of such objects. To learn about the way promises work and how you can use them, we advise you to read Using promises first. The constructor is primarily used to wrap functions that do not already support promises.

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

תחביר

+ +
new Promise( /* executor */ function(resolve, reject) { ... } );
+ +

פרמטרים

+ +
+
executor
+
A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.
+
+ +

תיאור

+ +

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

+ +

A Promise is in one of these states:

+ + + +

A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

+ +

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, they can be chained.

+ +

+ +
+

Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes which are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression to create the lazily-evaluated expression, and f() to evaluate.

+
+ +
+

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled or “locked in” to match the state of another promise. States and fates contains more details about promise terminology.

+
+ +

מאפיינים

+ +
+
Promise.length
+
Length property whose value is always 1 (number of constructor arguments).
+
{{jsxref("Promise.prototype")}}
+
Represents the prototype for the Promise constructor.
+
+ +

Methods

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Returns a Promise object that is rejected with the given reason.
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you don't know if a value is a promise or not, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.
+
+ +

Promise prototype

+ +

Properties

+ +

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

+ +

Methods

+ +

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

+ +

Creating a Promise

+ +

A Promise object is created using the new keyword and its constructor. This constructor takes as its argument a function, called the "executor function". This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails, and returns the reason for failure, which is typically an error object.

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // do something asynchronous which eventually calls either:
+  //
+  //   resolve(someValue); // fulfilled
+  // or
+  //   reject("failure reason"); // rejected
+});
+
+ +

To provide a function with promise functionality, simply have it return a promise:

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest();
+    xhr.open("GET", url);
+    xhr.onload = () => resolve(xhr.responseText);
+    xhr.onerror = () => reject(xhr.statusText);
+    xhr.send();
+  });
+}
+ +

דוגמאות

+ +

דוגמה בסיסית

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
+  // In this example, we use setTimeout(...) to simulate async code.
+  // In reality, you will probably be using something like XHR or an HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // Yay! Everything went well!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage is whatever we passed in the resolve(...) function above.
+  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
+  console.log("Yay! " + successMessage);
+});
+
+ +

דוגמה מתקדמת

+ + + +

This small example shows the mechanism of a Promise. The testPromise() method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will be fulfilled, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

+ +

The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    let thisPromiseCount = ++promiseCount;
+
+    let log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
+    let p1 = new Promise(
+        // The executor function is called with the ability to resolve or
+        // reject the promise
+       (resolve, reject) => {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // This is only an example to create asynchronism
+            window.setTimeout(
+                function() {
+                    // We fulfill the promise !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // We define what to do when the promise is resolved with the then() call,
+    // and what to do when the promise is rejected with the catch() call
+    p1.then(
+        // Log the fulfillment value
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
+        }).catch(
+        // Log the rejection reason
+       (reason) => {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+ + + +

This example is started by clicking the button. You need a browser that supports Promise. By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.

+ +

{{EmbedLiveSample("Advanced_Example", "500", "200")}}

+ +

טעינת תמונה באמצעות XHR

+ +

Another simple example using Promise and {{domxref("XMLHttpRequest")}} to load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

+ +

מפרט

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
+ +

תאימות דפדפן

+ + + +

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

+ +

ראה גם

+ + diff --git a/files/he/web/javascript/reference/global_objects/string/index.html b/files/he/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..8b8911749e --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,314 @@ +--- +title: 'String: מחרוזת' +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.

+ +

תחביר

+ +

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

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\XXXan octal Latin-1 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.

+ +

תיאור

+ +

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, the 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.
+ +

מאפיינים

+ +
+
{{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()")}}
+
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(num.replace("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')}}
+ +

דוגמאות

+ +

String conversion

+ +

It's possible to use String as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{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')}} 
+ +

תאימות דפדפן

+ + + +

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

+ +

ראה גם

+ + diff --git a/files/he/web/javascript/reference/index.html b/files/he/web/javascript/reference/index.html new file mode 100644 index 0000000000..1f46b431e0 --- /dev/null +++ b/files/he/web/javascript/reference/index.html @@ -0,0 +1,58 @@ +--- +title: JavaScript reference +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +
הדף הנ"ל משמש כמאגר של עובדות ורפרנסים לנושאים מרכזיים בשפת התכנות ג'אווה סקריפט. קרא עוד על עמוד זה.
+ +
 
+ +

אובייקטים גלובאלים

+ +

פרק זה הוא תיעוד של כלל האובייקטים שמובנים כסטנדרט בג'אווה סקריפט, יחד עם המתודות (methods) והתכונות (properties) שלהם.

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

הצהרות

+ +

פרק זה הוא תיעוד של כלל ההצהרות והמשפטים* בג'אווה סקריפט.

+ +

* התרגום של statement ו declaration לעברית הוא "הצהרה".
+ כאן הכוונה להצהרה ( declaration ), לדוגמא - var a = 123.
+ ומשפט (statement), לדוגמא - משפטי if.

+ +
{{page('/he/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

ביטויים ואופרטורים

+ +

פרק זה הוא תיעוד של כלל הביטויים והאופרטורים בג'אווה סקריפט.

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

פונקציות

+ +

פרק זה הוא תיעוד של מהלך העבודה עם פונקציות בג'אווה סקריפט בפיתוח תוכנות.

+ + + +

* סביר שיש תרגום טוב יותר למונח rest parameters./

+ +

רפרנסים נוספים

+ + diff --git a/files/he/web/javascript/reference/operators/destructuring_assignment/index.html b/files/he/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..07b2957fe2 --- /dev/null +++ b/files/he/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,416 @@ +--- +title: השמה מפורקת +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +

תחביר השמה מפורקת הוא ביטוי JavaScript המאפשר לחלץ נתונים ממערכים או אובייקטים לערכים מפורשים, בעזרת שימוש בתחביר שמשקף את מבנה המערך או האובייקט המילולי.

+ +

תחביר

+ +
var a, b, rest;
+[a, b] = [1, 2]
+console.log(a); // 1
+console.log(b); // 2
+
+[a, b, ...rest] = [1, 2, 3, 4, 5]
+console.log(a); // 1
+console.log(b); // 2
+console.log(rest); // [3, 4, 5]
+
+({a, b} = {a: 1, b :2});
+console.log(a); // 1 console.log(b); // 2
+
+({a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4});  //ES2016
+console.log(a); // 1
+console.log(b); // 2
+console.log(rest); // {c: 3, d: 4}
+
+ +
+

{a, b} = {a:1, b:2} הוא לא תחביר עצמאי תקף, כי {a, b} בצד השמאלי נחשב כבלוק ולא כאובייקט מילולי.

+ +

עם זאת, ({a, b} = {a:1, b:2}) תקף, כמו גם {var {a, b} = {a:1, b:2.

+
+ +

תאור

+ +
ביטויים ליטרלים של אובייקטים או מערכים מספקים דרך פשוטה ליצירה של חבילת נתונים לפי דרישה. לאחר יצירת חבילות נתונים אלה, ניתן להשתמש בהם בכל דרך שתרצה. ניתן אפילו להחזיר אותם מפונקציות.
+ +
var x = [10, 20, 30, 40, 50];
+ +

השמה מפורקת משתמשת בתחביר דומה, אך צד שמאל של ההשמה מציין אילו ערכים לפרוק ממשתנה המקור.

+ +
var x = [10, 20, 30, 40, 50];
+var [y, x] = x;
+console.log(y); // 10
+console.log(z); // 20
+
+ +

דבר אחד שימושי במיוחד שאתה יכול לעשות עם השמה מפורקת הוא לקרוא מבנה שלם בהשמה אחת, אם כי יש עוד מספר דברים מעניינים שאתה יכול לעשות איתם, כפי שמוצג בדוגמאות הבאות.

+ +

יכולת זו דומה לתכונות קיימות בשפות כמו פרל ופייתון.

+ +

פירוק מערך

+ +

דוגמה פשוטה

+ +
var foo = ["one", "two", "three"];
+
+// without destructuring
+var one   = foo[0];
+var two   = foo[1];
+var three = foo[2];
+
+// with destructuring
+var [one, two, three] = foo;
+ +

השמה ללא הצהרה

+ +

השמה מפורקת יכולה להתבצע ללא הצהרה בעת ההשמה.

+ +
var a, b;
+
+[a, b] = [1, 2];
+ +

החלפת משתנים

+ +

לאחר ביצוע הקוד הזה, b הוא 1 וa הוא 3. ללא השמה מפורקת, החלפת שני ערכים דורשת שימוש במשתנה זמני (או, בכמה שפות נמוכות, טריק ההחלפת XOR).

+ +
var a = 1;
+var b = 3;
+
+[a, b] = [b, a];
+ +

החזרה מרובת ערכים

+ +

תודה להשמה מפורקת פונקציות יכולות להחזיר ערכים מרובים. למרות שתמיד היה ניתן להחזיר מערך מפונקציה, זה עדיין מספק מידה נוספת של גמישות.

+ +
function f() {
+  return [1, 2];
+}
+
+ +

כפי שניתן לראות, החזרת תוצאות נעשית באמצעות סימון כמו מערך, עם כל הערכים בתוך סוגריים. אתה יכול להחזיר מספר בלתי מוגבל של תוצאות בדרך זו. בדוגמא זו, ()f מחזירה את הערכים [1, 2] כפלט שלה.

+ +
var a, b;
+[a, b] = f();
+console.log("A is " + a + " B is " + b);
+
+ +

ההצהרה ()a, b] = f] מקצה את התוצאות של הפונקציה למשתנים בסוגריים, בהתאמה: a הוא 1 ו- b מוגדר 2.

+ +

גם אתה יכול לקבל את ערכי החזרה כמערך:

+ +
var a = f();
+console.log("A is " + a);
+
+ +

במקרה זה, a הוא מערך המכיל את הערכים 1 ו-2.

+ +

התעלמות ממספר ערכי החזר

+ +

אתה יכול להתעלם מערכי החזר שאתה לא מעוניין בהם:

+ +
function f() {
+  return [1, 2, 3];
+}
+
+var [a, , b] = f();
+console.log("A is " + a + " B is " + b);
+
+ +

לאחר הרצת קוד זה, a הוא 1 ו- b הוא 3. הערך 2 נדחה. אתה יכול להתעלם מכל ערכי ההחזר בדרך זו. לדוגמה:

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

משיכת ערכים מתוצאה של regular expression

+ +

כאשר המתודה  exec של regular expression מוצאת התאמה, היא מחזירה מערך המכיל במיקום הראשון את כל ההתאמה של המחרוזת ולאחר מכן את כל החלקים של המחרוזת שתאמה כל קבוצה בסוגריים בregular expression. השמה מפורקת מאפשרת לך למשוך את החלקים מתוך מערך זה בקלות, תוך התעלמות מההתאמה המלאה אם היא לא נחוצה.

+ +
var url = "https://developer.mozilla.org/en-US/Web/JavaScript";
+
+var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+var [, protocol, fullhost, fullpath] = parsedURL;
+
+console.log(protocol); // logs "https"
+
+ +

פירוק אובייקט

+ +

דוגמה פשוטה

+ +
var o = {p: 42, q: true};
+var {p, q} = o;
+
+console.log(p); // 42
+console.log(q); // true
+
+// Assign new variable names
+var {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true  
+ +

השמה ללא הצהרה

+ +

השמה מפורקת יכולה להתבצע ללא הצהרה בעת ההשמה.

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

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

+
+ +

ברירות המחדל של ארגומנטים מפונקציה

+ +

גרסת ES5

+ +
function drawES5Chart(options) {
+  options = options === undefined ? {} : options;
+  var size = options.size === undefined ? 'big' : options.size;
+  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
+  var radius = options.radius === undefined ? 25 : options.radius;
+  console.log(size, cords, radius);
+  // now finally do some chart drawing
+}
+
+drawES5Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

גרסת ES2015

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

In Firefox, default values for destructuring assignments are not yet implemented: var { x = 3 } = {} and var [foo = "bar"] = []. See {{bug(932080)}} for destructured default values in functions.

+
+ +

Module (non-ES2015) loading

+ +

Destructuring can help to load specific subsets of a non-ES2015 module like here in the Add-on SDK:

+ +
const { Loader, main } = require('toolkit/loader');
+
+ +

Nested object and array destructuring

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

For of iteration and destructuring

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

Pulling fields from objects passed as function parameter

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

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

+ +

Computed object property names and destructuring

+ +

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

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

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{ CompatGeckoDesktop("1.8.1") }}{{CompatNo}}{{CompatNo}}7.1
Computed property names{{CompatNo}}{{ CompatGeckoDesktop("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Spread operator{{CompatUnknown}}{{ CompatGeckoDesktop("34") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("1.0") }}{{CompatNo}}{{CompatNo}}8
Computed property names{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Spread operator{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("34") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox-specific notes

+ + + +

ראה גם

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

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

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Primary expressions

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function
+
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

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

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

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

Unary operators

+ +

A unary operation is operation with only one operand.

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

Arithmetic operators

+ +

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

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

Relational operators

+ +

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

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

Equality operators

+ +

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

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

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

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

Binary bitwise operators

+ +

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

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

Binary logical operators

+ +

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

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

Conditional (ternary) operator

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

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

+
+
+ +

Assignment operators

+ +

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

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

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

+
+
+ +

Comma operator

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

Non-standard features

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

Specifications

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

See also

+ + diff --git a/files/he/web/javascript/reference/operators/operator_precedence/index.html b/files/he/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..2f22b36031 --- /dev/null +++ b/files/he/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,330 @@ +--- +title: Operator precedence +slug: Web/JavaScript/Reference/Operators/Operator_Precedence +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

קדימות אופרטורים קובעת את הסדר שבו מעריכים את תוצאות האופרטורים. אופרטורים בעלי קדימות גבוהה יותר יוערכו ראשונים.

+ +

דוגמא נפוצה:

+ +
3 + 4 * 5 // מחזיר 23
+
+ +

לאופרטור הכפל ("*") יש קדימות גבוהה יותר מאשר לאופרטור החיבור ("+") ולכן יוערך ראשון.

+ +

אסוציטיביות

+ +

אסוציטיביות קובעת את הסדר שבו מעריכים אופרטורים בעלי קדימות זהה. למשל, חשבו על הביטוי הבא:

+ +
a OP b OP c
+
+ +

אסוציטיביות שמאלית (משמאל לימין) פירושה שמעריכים (a OP b) OP c , ואסוציטיביות ימנית (מימין לשמאל) פירושה שמעריכים a OP (b OP c). לאופרטורי השמה יש אסוציטיביות ימנית, אז אפשר לכתוב:

+ +
a = b = 5;
+
+ +

ולצפות ש-a ו-b יקבלו את הערך 5. זאת משום שאופרטור ההשמה מחזיר את הערך שהושם. תחילה, הערך 5 מושם ל-b. אחר כך הערך של b מושם ל-a.

+ +

טבלה

+ +

הטבלה הבאה ממויינת לפי קדימות מהגבוה (19) לנמוך (0).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטוראסוציטיביותסוג האופרטורקדימות
( … )n/aGrouping19
… . …שמאליתMember Access18
… [ … ]שמאליתComputed Member Access
new … ( … )n/anew (עם רשימת ארכומנטים)
… ( … )שמאליתFunction Call17
new …ימניתnew (without argument list)
… ++n/aPostfix Increment16
… --n/aPostfix Decrement
! …ימניתLogical NOT15
~ …ימניתBitwise NOT
+ …ימניתUnary Plus
- …ימניתUnary Negation
++ …ימניתPrefix Increment
-- …ימניתPrefix Decrement
typeof …ימניתtypeof
void …ימניתvoid
delete …ימניתdelete
… ** …ימניתExponentiation14
… * …שמאליתMultiplication
… / …שמאליתDivision
… % …שמאליתRemainder
… + …שמאליתAddition13
… - …שמאליתSubtraction
… << …שמאליתBitwise Left Shift12
… >> …שמאליתBitwise Right Shift
… >>> …שמאליתBitwise Unsigned Right Shift
… < …שמאליתLess Than11
… <= …שמאליתLess Than Or Equal
… > …שמאליתGreater Than
… >= …שמאליתGreater Than Or Equal
… in …שמאליתin
… instanceof …שמאליתinstanceof
… == …שמאליתEquality10
… != …שמאליתInequality
… === …שמאליתStrict Equality
… !== …שמאליתStrict Inequality
… & …שמאליתBitwise AND9
… ^ …שמאליתBitwise XOR8
… | …שמאליתBitwise OR7
… && …שמאליתLogical AND6
… || …שמאליתLogical OR5
… ? … : …ימניתConditional4
… = …ימניתAssignment3
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
yield …ימניתyield2
... …n/aSpread1
… , …שמאליתComma / Sequence0
diff --git a/files/he/web/javascript/reference/statements/const/index.html b/files/he/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..98de11967b --- /dev/null +++ b/files/he/web/javascript/reference/statements/const/index.html @@ -0,0 +1,133 @@ +--- +title: const +slug: Web/JavaScript/Reference/Statements/const +tags: + - const + - מה זה const + - משתנים +translation_of: Web/JavaScript/Reference/Statements/const +--- +
{{jsSidebar("Statements")}}
+ +
מילת ההצהרה const משמשת להכזרה על משתנה קבוע שאין אפשרות לשנות את הערך שלו.
+ +
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
+ + + +

תחביר

+ +
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
+ +
+
nameN
+
שם המשתנה.
+
valueN
+
הערך של המשתנה.
+
+ +

תיאור

+ +

בשפת ג'אווה סקריפט אנו משתמשים במשתנים על מנת להחזיק ערכים שונים.
+ הצהרה על משתנה באמצעות const הופכת אותו לקבוע ולא ניתן לשנות את הערך שלו.
+ הקצאת ערך למשתנה ללא הצהרה מראש הופכת אותו למשתנה גלובלי, אך בשונה מהצהרה באמצעות var הוא אינו כפוף לאובייקט האב window.
+ חשוב לציין שהצהרה באמצעות const לא מבצעת Hoisting.

+ +

דוגמאות

+ +

הדוגמה הבאה ממחישה כיצד מתנהגים משתנים קבועים.

+ +
// NOTE: Constants can be declared with uppercase or lowercase, but a common
+// convention is to use all-uppercase letters.
+
+// define MY_FAV as a constant and give it the value 7
+const MY_FAV = 7;
+
+// this will throw an error - Uncaught TypeError: Assignment to constant variable.
+MY_FAV = 20;
+
+// MY_FAV is 7
+console.log('my favorite number is: ' + MY_FAV);
+
+// trying to redeclare a constant throws an error -  Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
+const MY_FAV = 20;
+
+// the name MY_FAV is reserved for constant above, so this will fail too
+var MY_FAV = 20;
+
+// this throws an error too
+let MY_FAV = 20;
+
+// it's important to note the nature of block scoping
+if (MY_FAV === 7) {
+    // this is fine and creates a block scoped MY_FAV variable
+    // (works equally well with let to declare a block scoped non const variable)
+    let MY_FAV = 20;
+
+    // MY_FAV is now 20
+    console.log('my favorite number is ' + MY_FAV);
+
+    // this gets hoisted into the global context and throws an error
+    var MY_FAV = 20;
+}
+
+// MY_FAV is still 7
+console.log('my favorite number is ' + MY_FAV);
+
+// throws an error - Uncaught SyntaxError: Missing initializer in const declaration
+const FOO;
+
+// const also works on objects
+const MY_OBJECT = {'key': 'value'};
+
+// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
+MY_OBJECT = {'OTHER_KEY': 'value'};
+
+// However, object keys are not protected,
+// so the following statement is executed without problem
+MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
+
+// The same applies to arrays
+const MY_ARRAY = [];
+// It's possible to push items into the array
+MY_ARRAY.push('A'); // ["A"]
+// However, assigning a new array to the variable throws an error - Uncaught TypeError: Assignment to constant variable.
+MY_ARRAY = ['B'];
+ +

מפרט

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ESDraft')}}No changes.
+ +

תאימות דפדפן

+ + + +

{{Compat("javascript.statements.const")}}

+ +

ראה גם

+ + diff --git a/files/he/web/javascript/reference/statements/for...of/index.html b/files/he/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..86edb2f69e --- /dev/null +++ b/files/he/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,269 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +
{{jsSidebar("Statements")}}
+ +
 
+ +
הצהרת for...of יוצרת לולאה ע"ג iterable objects (שכולל {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, arguments object וכן הלאה..),
+ +
invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+ +

Syntax

+ +
for (variable of iterable) {
+  statement
+}
+
+ +
+
variable
+
בכל איטרציה, ערך ה property הנוכחי של iterable מוקצה ל variable
+
iterable
+
אובייקט עם properties ברי איטרציה
+
+ +

לדוגמא:

+ +

איטרציה ע"ג {{jsxref("Array")}}

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

אפשר להשתמש ג"כ ב const במקום let באם אתה לא משנה את ערך המשתנה בתוך הבלוק.

+ +

 

+ +

איטרציה ע"ג {{jsxref("String")}}

+ +
let iterable = "boo";
+
+for (let value of iterable) {
+  console.log(value);
+}
+// "b"
+// "o"
+// "o"
+
+ +

Iterating over a {{jsxref("TypedArray")}}

+ +
let iterable = new Uint8Array([0x00, 0xff]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 0
+// 255
+
+ +

Iterating over a {{jsxref("Map")}}

+ +
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
+
+for (let entry of iterable) {
+  console.log(entry);
+}
+// [a, 1]
+// [b, 2]
+// [c, 3]
+
+for (let [key, value] of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Iterating over a {{jsxref("Set")}}

+ +
let iterable = new Set([1, 1, 2, 2, 3, 3]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Iterating over a DOM collection

+ +

Iterating over DOM collections like {{domxref("NodeList")}}: the following example adds a read class to paragraphs that are direct descendants of an article:

+ +
// Note: This will only work in platforms that have
+// implemented NodeList.prototype[Symbol.iterator]
+let articleParagraphs = document.querySelectorAll("article > p");
+
+for (let paragraph of articleParagraphs) {
+  paragraph.classList.add("read");
+}
+
+ +

Iterating over generators

+ +

You can also iterate over generators:

+ +
function* fibonacci() { // a generator function
+  let [prev, curr] = [1, 1];
+  while (true) {
+    [prev, curr] = [curr, prev + curr];
+    yield curr;
+  }
+}
+
+for (let n of fibonacci()) {
+  console.log(n);
+  // truncate the sequence at 1000
+  if (n >= 1000) {
+    break;
+  }
+}
+
+ +

Iterating over other iterable objects

+ +

You can also iterate over an object that explicitly implements iterable protocol:

+ +
var iterable = {
+  [Symbol.iterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return { value: this.i++, done: false };
+        }
+        return { value: undefined, done: true };
+      }
+    };
+  }
+};
+
+for (var value of iterable) {
+  console.log(value);
+}
+// 0
+// 1
+// 2
+
+ +

Difference between for...of and for...in

+ +

The for...in loop will iterate over all enumerable properties of an object.

+ +

The for...of syntax is specific to collections, rather than all objects. It will iterate in this manner over the elements of any collection that has a [Symbol.iterator] property.

+ +

The following example shows the difference between a for...of loop and a for...in loop.

+ +
Object.prototype.objCustom = function () {};
+Array.prototype.arrCustom = function () {};
+
+let iterable = [3, 5, 7];
+iterable.foo = "hello";
+
+for (let i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+
+for (let i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeOperaSafari
Basic support{{CompatChrome(38)}} [1]
+ {{CompatChrome(51)}} [3]
{{CompatGeckoDesktop("13")}} [2]12257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support5.1{{CompatChrome(38)}} [1]{{CompatGeckoMobile("13")}} [2]{{CompatNo}}{{CompatUnknown}}8
+
+ +

[1] From Chrome 29 to Chrome 37 this feature was available behind a preference. In chrome://flags/#enable-javascript-harmony, activate the entry “Enable Experimental JavaScript”.

+ +

[2] Prior Firefox 51, using the for...of loop construct with the const keyword threw a {{jsxref("SyntaxError")}} ("missing = in const declaration"). This has been fixed ({{bug(1101653)}}).

+ +

[3] Support for iteration of objects was added in Chrome 51.

+ +

See also

+ + diff --git a/files/he/web/javascript/reference/statements/for_each...in/index.html b/files/he/web/javascript/reference/statements/for_each...in/index.html new file mode 100644 index 0000000000..b45c6f5ab7 --- /dev/null +++ b/files/he/web/javascript/reference/statements/for_each...in/index.html @@ -0,0 +1,128 @@ +--- +title: for each...in +slug: Web/JavaScript/Reference/Statements/for_each...in +translation_of: Archive/Web/JavaScript/for_each...in +--- +
{{jsSidebar("Statements")}}
+ +
+

טענת "for each...in" הוצאה משימוש בסטנדרט (ECMA-357 (E4X. התמיכה ב-E4X אמנם הוסרה, אך טענת ה"for each...in" לא תבוטל ולא תוסר מטעמי תאימות לגרסאות קודמות. עם זאת, מומלץ להשתמש בטענת "for...of" במקום. (ע"ע {{ bug("791343")}} ). 

+
+ +

טענה מסוג:

+ +

for each...in

+ +

("עבור כל... ב...")

+ +

חגה סביב  כל הערכים של כל "פריטי הרכוש" (properties) של משתנה נתון. עבור כל אחד מפריטי הרכוש תבוצע טענה מוגדרת.

+ +

תחביר

+ +
for each (variable in object) {
+  statement
+}
+ +
+
variable
+
המשתנה שיחוג סביב הערכים של פרטי הרכוש. ניתן (אך לא חובה)  להצהיר על משתנה זה עם מילת המפתח var. המשתנה הזה הוא פנימי לפונקציה, ולא ללולאה עצמה.
+
+ +
+
object
+
האובייקט שסביב פריטי הרכוש שלו יש לחוג. 
+
+ +
+
statement
+
טענה שיש לבצע עבור כל אחד מפריטי הרכוש. על מנת לבצע יותר מטענה אחת בתוך הלולאה, יש להשתמש בטענת בלוק ({ ... }) כדי לקבץ את הטענות הללו יחדיו.
+
+ +

תיאור

+ +

 

+ +

Some built-in properties are not iterated over. These include all built-in methods of objects, e.g. String's indexf

+ +

method. However, all user-defined properties are iterated over.

+ +

Examples

+ +

Using for each...in

+ +

Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

+ +

The following snippet iterates over an object's properties, calculating their sum:

+ +
var sum = 0;
+var obj = {prop1: 5, prop2: 13, prop3: 8};
+
+for each (var item in obj) {
+  sum += item;
+}
+
+console.log(sum); // logs "26", which is 5+13+8
+ +

Specifications

+ +

Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("1.8")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("1.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/he/web/javascript/reference/statements/function_star_/index.html b/files/he/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..a72a927859 --- /dev/null +++ b/files/he/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,212 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

 

+ +

הצהרת function* (מילת function ולאחריה כוכבית) מגדירה פונקצית גנרטור, אשר מחזירה אובייקט {{jsxref("Global_Objects/Generator","Generator")}}.

+ +
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
+ + + +
+

ניתן גם להגדיר פונקציות גנרטור על-ידי שימוש בבנאי {{jsxref("GeneratorFunction")}}, או בתחביר של ביטוי פונקציה.

+
+ +

תחביר

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
שם הפונקציה.
+
+ +
+
param
+
השם של פרמטר רשמי של הפונקציה.
+
+ +
+
statements
+
הפקודות המרכיבות את גוף הפונקציה.
+
+ +

תיאור

+ +

גנרטורים הינם פונקציות שניתן לצאת מהן ולאחר מכן להיכנס אליהן מחדש. ההקשר שלהם (קשירת המשתנים) יישמר לאורך הכניסות מחדש.
+
+ גנרטורים ב- JavaScript -- במיוחד בשילוב עם Promises -- הינם כלי חזר מאוד לתכנות אסינכרוני, כיוון שהם מתווכים -- ואפילו מחסלים לחלוטין -- את הבעיות עם קריאות חוזרות, כגון Callback Hell ו- Inversion of Control.
+ תבנית זו הינה הבסיס לפונקציות async.

+ +

קריאה לפונקצית גנרטור לא מריצה את גוף הפונקציה מיידית; במקום זאת, מוחזר אובייקט איטרטור לפונקציה. כאשר המתודה ()next של האיטרטור נקראת, גוף הפונקציה רץ עד לביטוי ה-{{jsxref("Operators/yield", "yield")}} הראשון, אשר מציין את הערך שיוחזר לאיטרטור, או העברה לפונקציה יוצרת אחרת על-ידי שימוש {{jsxref("Operators/yield*", "*yield")}}. מתודת ה- ()next מחזירה אובייקט עם שדה value, המכיל את הערך המיוצר ושדה done בכעל ערך בוליאני, המציין האם הגנרטור יצר את הערך האחרון. קריאה למתודת ()next עם ארגומנט תמשיך את ריצת פונקציית הגנרטור, תוך החלפת ביטוי ה- yield בו הריצה הופסקה עם הארגומנט מתוך ()next.

+ +

פקודת return בתוך גנרטור, כאשר הוא רץ, תגרום לגנרטור לסיים (כלומר שדה ה- done המוחזר יהיה בעל true). אם ערך מוחזר, הוא יהיה בשדה value של האובייקט המוחזר על-ידי הגנרטור.
+ בדומה לפקודת ה- return, שגיאה שתיזרק בתוך הגנרטור תביא לסיום הגנרטור -- אלא אם היא תיתפס בגוף הגנרטור.
+ כאשר גנרטור מסתיים, קריאות נוספות ל- ()next לא יגרמו לריצה כלשהי של קוד הגנרטור. הן רק יחזירו אובייקט בצורה זו: {value: undefined, done: true}.

+ +

דוגמאות

+ +

דוגמה פשוטה

+ +
function* idMaker() {
+  var index = 0;
+  while (index < index+1)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // 3
+// ...
+ +

דוגמה עם *yield

+ +
function* anotherGenerator(i) {
+  yield i + 1;
+  yield i + 2;
+  yield i + 3;
+}
+
+function* generator(i) {
+  yield i;
+  yield* anotherGenerator(i);
+  yield i + 10;
+}
+
+var gen = generator(10);
+
+console.log(gen.next().value); // 10
+console.log(gen.next().value); // 11
+console.log(gen.next().value); // 12
+console.log(gen.next().value); // 13
+console.log(gen.next().value); // 20
+
+ +

העברת ארגומנטים לגנרטורים

+ +
function* logGenerator() {
+  console.log(0);
+  console.log(1, yield);
+  console.log(2, yield);
+  console.log(3, yield);
+}
+
+var gen = logGenerator();
+
+// הקריאה הראשונה ל- next מתבצעת מתחילת הפונקציה
+// עד שהיא מגיעה לפקודת yield הראשונה
+gen.next();             // 0
+gen.next('pretzel');    // 1 pretzel
+gen.next('california'); // 2 california
+gen.next('mayonnaise'); // 3 mayonnaise
+
+ +

פקודת return בתוך גנרטור

+ +
function* yieldAndReturn() {
+  yield "Y";
+  return "R";
+  yield "unreachable";
+}
+
+var gen = yieldAndReturn()
+console.log(gen.next()); // { value: "Y", done: false }
+console.log(gen.next()); // { value: "R", done: true }
+console.log(gen.next()); // { value: undefined, done: true }
+
+ +

לא ניתן ליצור אובייקט גנרטור

+ +
function* f() {}
+var obj = new f; // throws "TypeError: f is not a constructor
+
+ +

גנרטורים המוגדרים בתוך ביטוי

+ +
const foo = function* () {
+  yield 10;
+  yield 20;
+};
+
+const bar = foo();
+console.log(bar.next()); // {value: 10, done: false}
+ +

מפרטים

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2015')}}הגדרה ראשונית.
{{SpecName('ES2016', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2016')}}שונה, כך  תהיה מלכודת שבגנרטורים לא [[Construct]] ויזרקו שגיאה בשימוש עם new.
{{SpecName('ESDraft', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ESDraft')}} 
+ +

תאימות לדפדפנים

+ +
+ + +

{{Compat("javascript.statements.generator_function")}}

+
+ +

הערות ספציפיות ל- Firefox

+ +

גנרטורים ואיטרטורים ב- Firefox לפני גרסה 26

+ +

גרסאות Firefox ישנות יותר מממשות הגדרת גנרטורים ישנה יותר. בגרסה הקודמת גנרטורים הוגדרו על-ידי שימוש במילת function רגילה (ללא כוכבית), בין היתר. ראה פונקציה יוצרת מסורתית למידע נוסף.

+ +

אובייקט IteratorResult מוחזר במקום זריקת שגיאה

+ +

החל מ- Gecko 29 {{geckoRelease(29)}}, הפונקציה היוצרת המלאה כבר אינה זורקת {{jsxref("TypeError")}} "generator has already finished". במקום זאת, היא מחזירה אובייקט IteratorResult כדוגמת { value: undefined, done: true } ({{bug(958951)}}).

+ +

ראה גם

+ + diff --git a/files/he/web/javascript/reference/statements/index.html b/files/he/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..2869ba1ce5 --- /dev/null +++ b/files/he/web/javascript/reference/statements/index.html @@ -0,0 +1,148 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +
יישומי ג'אווה סקריפט מורכבים ממשפטים בעלי תחביר מתאים (syntax).
+ +
משפט אחד יכול להתפרס על גבי מספר שורות.
+ +
מספר משפטים יכולים להופיע על גבי שורה אחת אם בין משפט למשפט מפריד הסמן ";".
+ +
משפט הוא לא מילת מפתח אלא כמה מילות מפתח המאורגנות יחד.
+ +
 
+ +

משפטים והצהרות לפי קטגוריה

+ +

לרשימה אלפבתית ראה סרגל בצד שמאל

+ +

זרימת תהליך

+ +
+
{{jsxref("Statements/block", "Block")}}
+
משפט בלוק נועד לסידור של 0 או יותר משפטים יחד.
+ בלוק תחום בין שני סוגריים מסולסלים.
+
{{jsxref("Statements/break", "break")}}
+
משפט break עוצר את הלולאה, משפט switch או משפט סיווג (label statement) ומעביר את ריצת התוכנה למשפט שמגיע אחרי המשפט שנעצר.
+
{{jsxref("Statements/continue", "continue")}}
+
משפט continue עוצר את האיטרציה הנוכחית\מסווגת של הלולאה הנוכחית וממשיך לאיטרציה הבאה בלולאה.
+
{{jsxref("Statements/Empty", "Empty")}}
+
משפט empty נועד לשימוש כמשפט ריק במקומות בהם התחביר של ג'אווה סקריפט מצפה למשפט.
+
{{jsxref("Statements/if...else", "if...else")}}
+
משפטי if else מריצים משפטים בהתאם לתנאים מסויימים. אם תנאי מסויים לא מתקיים, יכול לרוץ משפט אחר.
+
{{jsxref("Statements/switch", "switch")}}
+
משפט switch מכיל ביטוי מסויים שבהתאם לערך שלו נבחרת פסקת case והמשפטים שבה מורצים.
+
{{jsxref("Statements/throw", "throw")}}
+
משפט throw זורק שגיאה מותאמת אישית.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
משפט try/catch מנסה להריץ בלוק מסויים, ומגדיר תגובה במקרה שנזרקת שגיאה.
+
+ +

 הצהרות

+ +
+
{{jsxref("Statements/var", "var")}}
+
המילה var מצהירה על משתנה חדש ומאפשרת לתת לו ערך ראשוני.
+
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
+
המילה let מצהירה על משתנה חדש ומקומי לבלוק שבו הוצהר (בניגוד ל var שנמצא בתחום הגלובאלי (global scope), אפשר לתת ערך ראשוני בזמן ההצהרה.
+
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
+
המילה const מצהירה על קבוע (constant) לקריאה בלבד.
+
+ +

פונקציות ומחלקות

+ +
+
{{jsxref("Statements/function", "function")}}
+
המילה function מצהירה על פונקציה עם הפרמטרים שצויינו.
+
{{experimental_inline}} {{jsxref("Statements/function*", "function*")}}
+
פונקציות מחוללות המאפשרות כתיבה פשוטה יותר של איטרטורים.
+
{{jsxref("Statements/return", "return")}}
+
המילה return מציינת את הערך שהפונקציה מחזירה.
+
{{experimental_inline}} {{jsxref("Statements/class", "class")}}
+
המילה class מגדירה מחלקה.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
משפט do...while יוצר לולאה שמריצה משפט מסויים עד שהתנאי שבה הופך לשלילי. 
+ בהרצה הראשונה המשפט מורץ בלי קשר לערך התנאי ורק לאחר מכן נבדק לפני כל הרצה מחדש. 
+
{{jsxref("Statements/for", "for")}}
+
משפט for יוצר לולאה שמורכבת משלושה ביטויים (אופציונאליים) התחומים בסוגריים ומופרדים ע"י סמן ";", שלאחריהם מורצים המשפטים שבתוך הלולאה.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
משפט for each...in עובר על כל הערכים של התכונות באובייקט מסויים ומריץ על כל אחת את המשפט שנמצא בלולאה.
+
{{jsxref("Statements/for...in", "for...in")}}
+
משפט for...in עובר על כל התכונות של אובייקט מסויים, בסדר שרירותי.
+ על תכונה יכולים לרוץ משפטים.
+
{{experimental_inline}} {{jsxref("Statements/for...of", "for...of")}}
+
משפט for...of עובר על אובייקטים הנתנים לאיטרציה (מערכים, אובייקטים, איטרטורים ומחוללים) ויוצר איטרציה מותאמת לכל אחד מהאובייקטים שבה יכולים לרוץ משפטים מסויימים על הערך של כל תכונה באובייקט.
+
{{jsxref("Statements/while", "while")}}
+
משפט while יוצר לולאה שמריצה משפט מסויים כל עוד התנאי שבה חיובי. 
+ התנאי מורץ לפני כל הרצה.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{experimental_inline}} {{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{experimental_inline}} {{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
+ +

See also

+ + diff --git a/files/he/web/javascript/reference/statements/return/index.html b/files/he/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..dea3cb868f --- /dev/null +++ b/files/he/web/javascript/reference/statements/return/index.html @@ -0,0 +1,151 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

הצהרה באמצעות return מתבצעת בעת סיום הפונקציה, גורמת לעצירתה ומציינת ערך שיש להחזיר למבקש הפונקציה.

+ +
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
+ + + +

תחביר

+ +
return [[expression]]; 
+ +
+
expression
+
הביטוי שערכו יוחזר. במידה והביטוי לא הוזכר, הערך undefined יוחזר במקומו.
+
+ +

תיאור

+ +

השימוש בהצהרה return בגוף הפונקציה, יפסיק את תהליך הריצה שלה.
+ לדוגמה, לפונקציה ()square ארגומנט בשם x, כאשר x יהיה מספר הפונקציה תחזיר את הערך של הארגומנט כפול עצמו.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

במידה וארגומנט חסר, הערך שיוחזר יהיה undefined
+ הצהרות ה-return הבאות מפסיקות את הריצה של הפונקציה:

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

הוספת נקודה פסיק באופן אוטומטי

+ +

להצהרה באמצעות return מתווספת באופן אוטומטי נקודה פסיק (ASI).
+ אין לקשר בין שורת ההצהרה של return לביטוי .

+ +
return
+a + b;
+
+ +
return;
+a + b;
+
+ +

כדי להימנע ממצב של הוספת נקודה פסיק באופן אוטומטי, יש להוסיף סוגריים באופן הבא:

+ +
return (
+  a + b
+);
+
+ +

דוגמאות

+ +

עצירת הפונקציה

+ +

הפונקציה נעצרת מיד בעת הקריאה ל-return.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

החזרת פונקציה

+ +

ראו את המאמר הבא בנושא Closures.

+ +
function magic() {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

מפרט

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("javascript.statements.return")}}

+ +

ראו גם

+ + diff --git a/files/he/web/javascript/reference/statements/var/index.html b/files/he/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..64020dee3e --- /dev/null +++ b/files/he/web/javascript/reference/statements/var/index.html @@ -0,0 +1,171 @@ +--- +title: var +slug: Web/JavaScript/Reference/Statements/var +tags: + - hoisted + - הכרזה + - משתנה +translation_of: Web/JavaScript/Reference/Statements/var +--- +
{{jsSidebar("Statements")}}
+ +

מילת ההצהרה var משמשת להכזרה על משתנה.

+ +
{{EmbedInteractiveExample("pages/js/statement-var.html")}}
+ + + +

תחביר

+ +
var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]];
+ +
+
varnameN
+
שם המשתנה.
+
+ +
+
valueN
+
 הערך של המשתנה.
+
+ +

תיאור

+ +

בשפת ג'אווה סקריפט אנו משתמשים במשתנים על מנת להחזיק ערכים שונים.
+ הקצאת ערך למשתנה ללא הצהרה מראש הופכת אותו למשתנה כגלובלי.
+ ניתן להשתמש במשתנה לפני שהוכרז, השימוש יעשה באמצעות Hoisting.

+ +

מהם ההבדלים בין משתנים מוצהרים לאלה שאינם?
+ 1. ראשית, משתנים מוצהרים יעשו רק את הפעולה שלשמה נוצרו, לעומת משתנים לא מוצהרים הנחשבים גלובלים.

+ +
function x() {
+  y = 1;   // Throws a ReferenceError in strict mode
+  var z = 2;
+}
+
+x();
+
+console.log(y); // logs "1"
+console.log(z); // Throws a ReferenceError: z is not defined outside x
+
+ +

2. משתנים מוצהרים מוכרזים לפני ביצוע קוד כלשהו לעומת זאת משתנים לא מוצהרים אינם קיימים עד שהקוד שמכריז עליהם מתבצע.

+ +
console.log(a);                // Throws a ReferenceError.
+console.log('still going...'); // Never executes.
+ +
var a;
+console.log(a);                // logs "undefined" or "" depending on browser.
+console.log('still going...'); // logs "still going...".
+ +

בשל שני ההבדלים הללו, אי הכרזה על משתנים עשויה להוביל לשגיאות בלתי צפויות.
+ לכן, מומלץ תמיד להכריז על משתנים, גם אם הם נמצאים בפונקציה.

+ +

var hoisting

+ +

זוהי התנהגות ברירת המחדל של השפה, שתפקידה להעביר את כל ההצהרות לחלק העליון של הסקריפט או הפונקציה ולכן משמעות הדבר היא שניתן להשתמש במשתנה לפני שהוכרז.

+ +
bla = 2;
+var bla;
+// ...
+
+// is implicitly understood as:
+
+var bla;
+bla = 2;
+
+ +

מומלץ להצהיר על משתנים בחלקו העליון של הסקריפט או הפונקציה וכך יהיה ברור אילו משתנים שייכים לפונקציה באופן מקומי ואילו גלובלים.

+ +

חשוב לזכור ששימוש ב-Hoisting ישפיע על הצהרת המשתנה אך לא על אתחול הערך:

+ +
function do_something() {
+  console.log(bar); // undefined
+  var bar = 111;
+  console.log(bar); // 111
+}
+
+// is implicitly understood as:
+function do_something() {
+  var bar;
+  console.log(bar); // undefined
+  bar = 111;
+  console.log(bar); // 111
+}
+
+ +

דוגמאות

+ +

הכרזה אחת של שני משתנים

+ +
var a = 0, b = 0;
+
+ +

הקצאת שני משתנים עם ערך מחרוזת יחיד

+ +
var a = 'A';
+var b = a;
+
+// Equivalent to:
+
+var a, b = a = 'A';
+
+ +

משתנה מקומי וגלובלי

+ +
var x = 0;
+
+function f() {
+  var x = y = 1; // x is declared locally. y is not!
+}
+f();
+
+console.log(x, y); // Throws a ReferenceError in strict mode (y is not defined). 0, 1 otherwise.
+// In non-strict mode:
+// x is the global one as expected
+// y leaked outside of the function, though!
+ +

מפרט

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-12.2', 'var statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}}{{Spec2('ESDraft')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("javascript.statements.var")}}

+ +

ראה גם

+ + -- cgit v1.2.3-54-g00ecf