From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../operators/arithmetic_operators/index.html | 293 +++++++++++++++++++ .../web/javascript/reference/operators/index.html | 310 +++++++++++++++++++++ .../index.html" | 248 +++++++++++++++++ 3 files changed, 851 insertions(+) create mode 100644 files/bg/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/bg/web/javascript/reference/operators/index.html create mode 100644 "files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" (limited to 'files/bg/web/javascript/reference/operators') diff --git a/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html b/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..83f26e031d --- /dev/null +++ b/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,293 @@ +--- +title: Arithmetic operators +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Аритметичните оператори приемат числови стойности като техен операнд и връща единична числова стойност. Стандартните аритметични оператори са събиране (+), изваждане (-), умножение (*), делене(/)

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

Събиране (+)

+ +

Операторът за събиране произвежда сумата от числови операнди или конкатенация на стрингове.

+ +

Синтаксис

+ +
Operator: x + y
+
+ +

Примери

+ +
// Number + Number -> събиране
+1 + 2 // 3
+
+// Boolean + Number -> събиране
+true + 1 // 2
+
+// Boolean + Boolean -> събиране
+false + false // 0
+
+// Number + String -> конкатенация
+5 + 'foo' // "5foo"
+
+// String + Boolean -> конкатенация
+'foo' + false // "foofalse"
+
+// String + String -> конкатенация
+'foo' + 'bar' // "foobar"
+
+ +

Subtraction (-)

+ +

The subtraction operator subtracts the two operands, producing their difference.

+ +

Syntax

+ +
Operator: x - y
+
+ +

Examples

+ +
5 - 3     // 2
+3 - 5     // -2
+'foo' - 3 // NaN
+ +

Division (/)

+ +

The division operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

+ +

Syntax

+ +
Operator: x / y
+
+ +

Examples

+ +
1 / 2      // returns 0.5 in JavaScript (In Java, returns 0; both are integers)
+// (neither 1 nor 2 is explicitly a floating point number)
+
+Math.floor(3 / 2) // returns 1
+1.0 / 2.0  // returns 0.5 in both JavaScript and Java
+
+2.0 / 0    // returns Infinity
+2.0 / 0.0  // ditto, because 0.0 === 0
+2.0 / -0.0 // returns -Infinity
+ +

Multiplication (*)

+ +

The multiplication operator produces the product of the operands.

+ +

Syntax

+ +
Operator: x * y
+
+ +

Examples

+ +
 2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN
+Infinity * Infinity // Infinity
+'foo' * 2 // NaN
+
+ +

Remainder (%)

+ +

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

+ +

Syntax

+ +
Operator: var1 % var2
+
+ +

Examples

+ +
 12 % 5 //  2
+-12 % 5 // -2
+-1 % 2  // -1
+ 1 % -2 //  1
+NaN % 2 // NaN
+ 1 % 2  //  1
+ 2 % 3  //  2
+-4 % 2  // -0
+5.5 % 2 // 1.5
+
+ +

Exponentiation (**)

+ +

The exponentiation operator returns the result of raising the first operand to the power of the second operand. That is, var1var2, in the preceding statement, where var1 and var2 are variables. The exponentiation operator is right-associative. a ** b ** c is equal to a ** (b ** c).

+ +

Syntax

+ +
Operator: var1 ** var2
+
+ +

Notes

+ +

In most languages, such as PHP, Python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. For example, in Bash, the ** operator is defined to have a lower precedence than unary operators.

+ +

In JavaScript, it is impossible to write an ambiguous exponentiation expression; that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number.

+ +
-2 ** 2;
+// 4 in Bash, -4 in other languages.
+// This is invalid in JavaScript, as the operation is ambiguous.
+
+
+-(2 ** 2);
+// -4 in JavaScript and the author's intention is unambiguous.
+
+ +

Examples

+ +
2 ** 3 // 8
+3 ** 2 // 9
+3 ** 2.5 // 15.588457268119896
+10 ** -1 // 0.1
+NaN ** 2 // NaN
+
+2 ** 3 ** 2 // 512
+2 ** (3 ** 2) // 512
+(2 ** 3) ** 2 // 64
+
+ +

To invert the sign of the result of an exponentiation expression:

+ +
-(2 ** 2) // -4
+
+ +

To force the base of an exponentiation expression to be a negative number:

+ +
(-2) ** 2 // 4
+
+ +
+

Note: JavaScript also has a bitwise operator ^ (logical XOR). ** and ^ are different (for example : 2 ** 3 === 8 when 2 ^ 3 === 1.)

+
+ +

Increment (++)

+ +

The increment operator increments (adds one to) its operand and returns a value.

+ + + +

Syntax

+ +
Operator: x++ or ++x
+
+ +

Examples

+ +
// Postfix
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// Prefix
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

Decrement (--)

+ +

The decrement operator decrements (subtracts one from) its operand and returns a value.

+ + + +

Syntax

+ +
Operator: x-- or --x
+
+ +

Examples

+ +
// Postfix
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// Prefix
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

Unary negation (-)

+ +

The unary negation operator precedes its operand and negates it.

+ +

Syntax

+ +
Operator: -x
+
+ +

Examples

+ +
var x = 3;
+y = -x; // y = -3, x = 3
+
+// Unary negation operator can convert non-numbers into a number
+var x = "4";
+y = -x; // y = -4
+
+ +

Unary plus (+)

+ +

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to {{jsxref("NaN")}}.

+ +

Syntax

+ +
Operator: +x
+
+ +

Examples

+ +
+3     // 3
++'3'   // 3
++true  // 1
++false // 0
++null  // 0
++function(val){ return val } // NaN
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/operators/index.html b/files/bg/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..64ff89da64 --- /dev/null +++ b/files/bg/web/javascript/reference/operators/index.html @@ -0,0 +1,310 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - Overview + - Reference + - 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 a special property of an execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Operators/async_function", "async function")}}
+
The async function defines an async function expression.
+
{{jsxref("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

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

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

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

Unary operators

+ +

A unary operation is operation with only one operand.

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

Arithmetic operators

+ +

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

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

Relational operators

+ +

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

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

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

+
+ +

Equality operators

+ +

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

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

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

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

Binary bitwise operators

+ +

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

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

Binary logical operators

+ +

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

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

Conditional (ternary) operator

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

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

+
+
+ +

Assignment operators

+ +

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

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

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

+
+
+ +

Comma operator

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

Non-standard features {{non-standard_inline}}

+ +
+
{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} {{non-standard_inline}}{{obsolete_inline(60)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
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.
+
{{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
Array comprehensions.
+
{{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
Generator comprehensions.
+
+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git "a/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" "b/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" new file mode 100644 index 0000000000..e8a9b0dfe1 --- /dev/null +++ "b/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" @@ -0,0 +1,248 @@ +--- +title: Разпределящ синтаксис +slug: Web/JavaScript/Reference/Operators/разпределящ_синтаксис +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +

Разпределящият синтаксис позволява на итериращ се израз като масив или символен низ да бъде разширен на места, където се използват нула или повече аргументи (или извиквания на функции), елементи (дефиниция на масиви), както и обект да бъде разширен на места, където се очакват нула или повече двойки от тип ключ-стойност (дефиниция на обекти).

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

Синтаксис

+ +

За извиквания на функции:

+ +
myFunction(...iterableObj);
+
+ +

За стойности на масиви или символни низове:

+ +
[...iterableObj, '4', 'five', 6];
+ +

За стойности на обекти (ново от ECMAScript 2018):

+ +
let objClone = { ...obj };
+ +

Примери

+ +

Разпределящ синтаксис при извикване на функции

+ +

Замяна на apply()

+ +

Често се използва {{jsxref("Function.prototype.apply()")}} в случаите, когато искаме да използваме елементите на даден масив като аргументи на функция. 

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction.apply(null, args);
+ +

С разпределящия синтаксис можем да запишем горния израз по следния начин: 

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction(...args);
+ +

Всеки аргумент в списъка от аргументи може да използва разпределящия синтаксис и той може да бъде използван няколко пъти.

+ +
function myFunction(v, w, x, y, z) { }
+var args = [0, 1];
+myFunction(-1, ...args, 2, ...[3]);
+ +

Използване на аpply вместо new за конструиране на обект

+ +

Когато извикваме конструктор с {{jsxref("Operators/new", "new")}} не е възможно директно да бъде използван масив и функцията apply(apply прави [[Извикване]], а не [[Конструиране]]). С помощта на разпределящия синтаксис обаче масивът може да бъде използван лесно за конструиране на обект:

+ +
var dateFields = [1970, 0, 1];  // 1 Jan 1970
+var d = new Date(...dateFields);
+
+ +

За да използваме new с масив от параметри без разпределящ синтаксис, трябва да го направим косвено чрез прилагане на части:

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (вътрешна бележка за myConstructor):           arguments.length: 6
+// (вътрешна бележка myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (бележка на "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

Разпределящ синтаксис при стойности на масиви

+ +

По-мощен запис при създаване на масив

+ +

Без разпределящ синтаксис създаването на нов масив с помощта на вече съществуващ като част от него, синтаксисът за създаване на масив вече не върши работа. Трябва да пишем повече, например да използваме някой от следните методи: {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} и т.н. Използвайки разпределящия синтаксис записът става много по-кратък:

+ +
var parts = ['shoulders', 'knees'];
+var lyrics = ['head', ...parts, 'and', 'toes'];
+// ["head", "shoulders", "knees", "and", "toes"]
+
+ +

Както се използва разпределящ синтаксис за списък от аргументи, ... може да бъде използван и при създаване на масив, и то многократно.

+ +

Копиране на масив

+ +
var arr = [1, 2, 3];
+var arr2 = [...arr]; // като arr.slice()
+arr2.push(4);
+
+// arr2 става [1, 2, 3, 4]
+// arr остава неафектиран
+
+ +
+

Забележка: Разпределящият синтаксис ефективно минава едно ниво по-дълбоко докато копира масив. Затова може да не е подходящ за копиране на многомерни масиви както показва следния пример(същото е с {{jsxref("Object.assign()")}} и разпределящ синтаксис).

+
+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// Сега масивът a също е афектиран: [[], [2], [3]]
+
+ +

По-добър начин за конкатениране на масиви

+ +

{{jsxref("Array.prototype.concat()")}} често е използван за конкатениране на масив към края на вече съществуващ масив. Без използване на разпределящ синтаксис това може да бъде направено по следния начин:

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Добавя всички елементи от arr2 след тези на arr1
+arr1 = arr1.concat(arr2);
+ +

С разпределящ синтаксис това има вида: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr1, ...arr2]; // arr1 сега е [0, 1, 2, 3, 4, 5]
+
+ +

{{jsxref("Array.prototype.unshift()")}} често се използва за добавяне на масив със стойности в началото на вече съществуващ масив. Без разпределящ синтаксис това може да бъде направено по следния начин: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Добавя всички елементи от arr2 преди тези на arr1
+Array.prototype.unshift.apply(arr1, arr2) // arr1 сега е [3, 4, 5, 0, 1, 2]
+ +

С разпределящ синтаксис става по следния начин: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr2, ...arr1]; // arr1 сега е [3, 4, 5, 0, 1, 2]
+
+ +
+

Забележка: За разлика от unshift(), това създава нов arr1, а не модифицира оригиналния масив arr1

+
+ +

Разпределящ синтаксис при дефиниця на обекти

+ +

Предложението за Rest/Spread Properties for ECMAScript (етап 4) добавя разпределящи свойства към дефиницията на обекти. То копира собствени изброими свойства от даден обект към нов обект.

+ +

Повърхностното клониране(изключващо prototype) или смесването на обекти вече е възможно с помощта на по-кратък синтаксис от {{jsxref("Object.assign()")}}.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Обект { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Обект { foo: "baz", x: 42, y: 13 }
+ +

Обърнете внимание, че {{jsxref("Object.assign()")}} извиква setters за разлика от разпределящия синтаксис.

+ +

Забележете, че функцията  {{jsxref("Object.assign()")}} не може нито да бъде подменена, нито да се напише подобна:

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+const merge = ( ...objects ) => ( { ...objects } );
+
+var mergedObj = merge ( obj1, obj2);
+// Обект { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
+
+var mergedObj = merge ( {}, obj1, obj2);
+// Обект { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
+ +

В горния пример разпределящият синтаксис не работи както се очаква: той разпределя масив от аргументи в дефиницията на обекта според зададените параметри. 

+ +

Само за итериращи променливи

+ +

Разпределящият синтаксис (както и разпределящите свойства) може да бъде приложен само върху обекти, които могат да бъдат итерирани:

+ +
var obj = {'key1': 'value1'};
+var array = [...obj]; // TypeError: obj не може да се итерира
+
+ +

Разпределящ синтаксис с много стойности 

+ +

Когато използваме разпределящ синтаксис за извикване на функции трябва да бъдем запознати с възможността за надвишаване на лимита на брой на аргументи на функция в Javascript. За повече информация вижте {{jsxref("Function.prototype.apply", "apply()")}}.

+ +

Обединяващ синтаксис (параметри) 

+ +

Обединяващият синтаксис изглежда точно както разпределящия синтаксис, но е използван за разлагане на масиви и обекти. Иначе казано, обединяващият синтаксис е точно обратното на разпределящия синтаксис: докато разпределящият синтаксис разширява масива си със стойности, обединяващият синтаксис събира няколко елемента и ги събира в един елемент. За повече информация вижте rest parameters.

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}Дефинирана в няколко секции на спецификацията: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Дефинирана в Object Initializer
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}Няма промени.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}Няма промени.
+ +

Съвместимост с браузъри

+ + + +

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

+ +

Вижте още

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