diff options
Diffstat (limited to 'files/bg/web/javascript/reference/operators')
3 files changed, 851 insertions, 0 deletions
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 +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Аритметичните оператори </strong>приемат числови стойности като техен операнд и връща единична числова стойност. Стандартните аритметични оператори са събиране (<strong>+</strong>), изваждане (<strong>-</strong>), умножение (<strong>*</strong>), делене(<strong>/</strong>)</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Addition" name="Addition">Събиране (+)</h2> + +<p>Операторът за събиране произвежда сумата от числови операнди или конкатенация на стрингове.</p> + +<h3 id="Синтаксис">Синтаксис</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> + <var>y</var> +</pre> + +<h3 id="Примери">Примери</h3> + +<pre class="brush: js">// 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" +</pre> + +<h2 id="Subtraction" name="Subtraction">Subtraction (-)</h2> + +<p>The subtraction operator subtracts the two operands, producing their difference.</p> + +<h3 id="Syntax">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> - <var>y</var> +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">5 - 3 // 2 +3 - 5 // -2 +'foo' - 3 // NaN</pre> + +<h2 id="Division" name="Division">Division (/)</h2> + +<p>The division operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.</p> + +<h3 id="Syntax_2">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> / <var>y</var> +</pre> + +<h3 id="Examples_2">Examples</h3> + +<pre class="brush: js">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</pre> + +<h2 id="Multiplication" name="Multiplication">Multiplication (*)</h2> + +<p>The multiplication operator produces the product of the operands.</p> + +<h3 id="Syntax_3">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> * <var>y</var> +</pre> + +<h3 id="Examples_3">Examples</h3> + +<pre class="brush: js"> 2 * 2 // 4 +-2 * 2 // -4 +Infinity * 0 // NaN +Infinity * Infinity // Infinity +'foo' * 2 // NaN +</pre> + +<h2 id="Remainder" name="Remainder">Remainder (%)</h2> + +<p>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.</p> + +<h3 id="Syntax_4">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>var1</var> % <var>var2</var> +</pre> + +<h3 id="Examples_4">Examples</h3> + +<pre class="brush: js"> 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 +</pre> + +<h2 id="Exponentiation" name="Exponentiation">Exponentiation (**)</h2> + +<p>The exponentiation operator returns the result of raising the first operand to the power of the second operand. That is, <code><var>var1</var></code><sup><code><var>var2</var></code></sup>, in the preceding statement, where <code><var>var1</var></code> and <code><var>var2</var></code> are variables. The exponentiation operator is right-associative. <code><var>a</var> ** <var>b</var> ** <var>c</var></code> is equal to <code><var>a</var> ** (<var>b</var> ** <var>c</var>)</code>.</p> + +<h3 id="Syntax_5">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>var1</var> ** <var>var2</var> +</pre> + +<h3 id="Notes">Notes</h3> + +<p>In most languages, such as PHP, Python, and others that have an exponentiation operator (<code>**</code>), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary <code>+</code> and unary <code>-</code>, but there are a few exceptions. For example, in Bash, the <code>**</code> operator is defined to have a lower precedence than unary operators.</p> + +<p>In JavaScript, it is impossible to write an ambiguous exponentiation expression; that is, you cannot put a unary operator (<code>+/-/~/!/delete/void/typeof</code>) immediately before the base number.</p> + +<pre class="brush: js">-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. +</pre> + +<h3 id="Examples_5">Examples</h3> + +<pre class="brush: js">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 +</pre> + +<p>To invert the sign of the result of an exponentiation expression:</p> + +<pre class="brush: js">-(2 ** 2) // -4 +</pre> + +<p>To force the base of an exponentiation expression to be a negative number:</p> + +<pre class="brush: js">(-2) ** 2 // 4 +</pre> + +<div class="note"> +<p><strong>Note:</strong> JavaScript also has <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">a bitwise operator ^ (logical XOR)</a>. <code>**</code> and <code>^</code> are different (for example : <code>2 ** 3 === 8</code> when <code>2 ^ 3 === 1</code>.)</p> +</div> + +<h2 id="Increment" name="Increment">Increment (++)</h2> + +<p>The increment operator increments (adds one to) its operand and returns a value.</p> + +<ul> + <li>If used postfix, with operator after operand (for example, <code><var>x</var>++</code>), then it increments and returns the value before incrementing.</li> + <li>If used prefix, with operator before operand (for example, <code>++<var>x</var></code>), then it increments and returns the value after incrementing.</li> +</ul> + +<h3 id="Syntax_6">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var>++ or ++<var>x</var> +</pre> + +<h3 id="Examples_6">Examples</h3> + +<pre class="brush: js">// Postfix +var x = 3; +y = x++; // y = 3, x = 4 + +// Prefix +var a = 2; +b = ++a; // a = 3, b = 3 +</pre> + +<h2 id="Decrement" name="Decrement">Decrement (--)</h2> + +<p>The decrement operator decrements (subtracts one from) its operand and returns a value.</p> + +<ul> + <li>If used postfix, with operator after operand (for example, <code><var>x</var>--</code>), then it decrements and returns the value before decrementing.</li> + <li>If used prefix, with operator before operand (for example, <code>--<var>x</var></code>), then it decrements and returns the value after decrementing.</li> +</ul> + +<h3 id="Syntax_7">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var>-- or --<var>x</var> +</pre> + +<h3 id="Examples_7">Examples</h3> + +<pre class="brush: js">// Postfix +var x = 3; +y = x--; // y = 3, x = 2 + +// Prefix +var a = 2; +b = --a; // a = 1, b = 1 +</pre> + +<h2 id="Unary_negation" name="Unary_negation">Unary negation (-)</h2> + +<p>The unary negation operator precedes its operand and negates it.</p> + +<h3 id="Syntax_8">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> -<var>x</var> +</pre> + +<h3 id="Examples_8">Examples</h3> + +<pre class="brush: js">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 +</pre> + +<h2 id="Unary_plus" name="Unary_plus">Unary plus (+)</h2> + +<p>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 (<code>-</code>) 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 <code>true</code>, <code>false</code>, and <code>null</code>. Integers in both decimal and hexadecimal (<code>0x</code>-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")}}.</p> + +<h3 id="Syntax_9">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> +<var>x</var> +</pre> + +<h3 id="Examples_9">Examples</h3> + +<pre class="brush: js">+3 // 3 ++'3' // 3 ++true // 1 ++false // 0 ++null // 0 ++function(val){ return val } // NaN +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.arithmetic")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment operators</a></li> +</ul> 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 +--- +<div>{{jsSidebar("Operators")}}</div> + +<p class="summary">This chapter documents all the JavaScript language operators, expressions and keywords.</p> + +<h2 id="Expressions_and_operators_by_category">Expressions and operators by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Primary_expressions">Primary expressions</h3> + +<p>Basic keywords and general expressions in JavaScript.</p> + +<dl> + <dt>{{jsxref("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to a special property of an execution context.</dd> + <dt>{{jsxref("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{jsxref("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{jsxref("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{jsxref("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function.</dd> + <dt>{{jsxref("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{jsxref("Operators/async_function", "async function")}}</dt> + <dd>The <code>async function</code> defines an async function expression.</dd> + <dt>{{jsxref("Operators/await", "await")}}</dt> + <dd>Pause and resume an async function and wait for the promise's resolution/rejection.</dd> + <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Left-hand-side_expressions">Left-hand-side expressions</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> + <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> + <dt>{{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{jsxref("Operators/Spread_syntax", "...obj")}}</dt> + <dd>Spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.</dd> +</dl> + +<h3 id="Increment_and_decrement">Increment and decrement</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Unary_operators">Unary operators</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> + <dd>Exponentiation operator.</dd> +</dl> + +<h3 id="Relational_operators">Relational operators</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<div class="note"> +<p><strong>Note: =></strong> is not an operator, but the notation for <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>.</p> +</div> + +<h3 id="Equality_operators">Equality operators</h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Binary_logical_operators">Binary logical operators</h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Conditional_ternary_operator">Conditional (ternary) operator</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.</p> + </dd> +</dl> + +<h3 id="Comma_operator">Comma operator</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Non-standard_features" name="Non-standard_features">Non-standard features {{non-standard_inline}}</h3> + +<dl> + <dt>{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} {{non-standard_inline}}{{obsolete_inline(60)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</dd> + <dt>{{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}} {{non-standard_inline}}{{obsolete_inline(58)}}</dt> + <dd>The <code>function</code> keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.</dd> + <dt>{{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}} {{non-standard_inline}}{{obsolete_inline(58)}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}} {{non-standard_inline}}{{obsolete_inline(58)}}</dt> + <dd>Generator comprehensions.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread syntax, rest syntax, destructuring assignment, <code>super</code> keyword.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> +</ul> diff --git a/files/bg/web/javascript/reference/operators/разпределящ_синтаксис/index.html b/files/bg/web/javascript/reference/operators/разпределящ_синтаксис/index.html new file mode 100644 index 0000000000..e8a9b0dfe1 --- /dev/null +++ b/files/bg/web/javascript/reference/operators/разпределящ_синтаксис/index.html @@ -0,0 +1,248 @@ +--- +title: Разпределящ синтаксис +slug: Web/JavaScript/Reference/Operators/разпределящ_синтаксис +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Разпределящият синтаксис </strong>позволява на итериращ се израз като масив или символен низ да бъде разширен на места, където се използват нула или повече аргументи (или извиквания на функции), елементи (дефиниция на масиви), както и обект да бъде разширен на места, където се очакват нула или повече двойки от тип ключ-стойност (дефиниция на обекти).</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}</div> + +<p class="hidden">Кода на този интерактивен пример се пази в GitHub хранилище. Ако искате да допринесете към интерактивния примерен проект, моля клонирайте <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> и ни изпратете pull request.</p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<p>За извиквания на функции:</p> + +<pre class="syntaxbox">myFunction(...iterableObj); +</pre> + +<p>За стойности на масиви или символни низове:</p> + +<pre class="syntaxbox">[...iterableObj, '4', 'five', 6];</pre> + +<p>За стойности на обекти (ново от ECMAScript 2018):</p> + +<pre class="syntaxbox">let objClone = { ...obj };</pre> + +<h2 id="Примери">Примери</h2> + +<h3 id="Разпределящ_синтаксис_при_извикване_на_функции">Разпределящ синтаксис при извикване на функции</h3> + +<p><code style="">Замяна на apply()</code></p> + +<p>Често се използва {{jsxref("Function.prototype.apply()")}} в случаите, когато искаме да използваме елементите на даден масив като аргументи на функция. </p> + +<pre class="brush: js">function myFunction(x, y, z) { } +var args = [0, 1, 2]; +myFunction.apply(null, args);</pre> + +<p>С разпределящия синтаксис можем да запишем горния израз по следния начин: </p> + +<pre class="brush: js">function myFunction(x, y, z) { } +var args = [0, 1, 2]; +myFunction(...args);</pre> + +<p>Всеки аргумент в списъка от аргументи може да използва разпределящия синтаксис и той може да бъде използван няколко пъти.</p> + +<pre class="brush: js">function myFunction(v, w, x, y, z) { } +var args = [0, 1]; +myFunction(-1, ...args, 2, ...[3]);</pre> + +<h4 id="Използване_на_аpply_вместо_new_за_конструиране_на_обект">Използване на <code>аpply</code> вместо <code>new</code> за конструиране на обект</h4> + +<p>Когато извикваме конструктор с {{jsxref("Operators/new", "new")}} не е възможно директно да бъде използван масив и функцията apply(apply прави <code>[[Извикване]],</code> а не <code>[[Конструиране]]</code>). С помощта на разпределящия синтаксис обаче масивът може да бъде използван лесно за конструиране на обект:</p> + +<pre class="brush: js">var dateFields = [1970, 0, 1]; // 1 Jan 1970 +var d = new Date(...dateFields); +</pre> + +<p>За да използваме <code>new</code> с масив от параметри без разпределящ синтаксис, трябва да го направим косвено чрез прилагане на части:</p> + +<pre class="brush: js">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"}</pre> + +<h3 id="Разпределящ_синтаксис_при_стойности_на_масиви">Разпределящ синтаксис при стойности на масиви</h3> + +<h4 id="По-мощен_запис_при_създаване_на_масив">По-мощен запис при създаване на масив</h4> + +<p>Без разпределящ синтаксис създаването на нов масив с помощта на вече съществуващ като част от него, синтаксисът за създаване на масив вече не върши работа. Трябва да пишем повече, например да използваме някой от следните методи: {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} и т.н. Използвайки разпределящия синтаксис записът става много по-кратък:</p> + +<pre class="brush: js">var parts = ['shoulders', 'knees']; +var lyrics = ['head', ...parts, 'and', 'toes']; +// ["head", "shoulders", "knees", "and", "toes"] +</pre> + +<p>Както се използва разпределящ синтаксис за списък от аргументи, <code>...</code> може да бъде използван и при създаване на масив, и то многократно.</p> + +<h4 id="Копиране_на_масив">Копиране на масив</h4> + +<pre class="brush: js">var arr = [1, 2, 3]; +var arr2 = [...arr]; // като arr.slice() +arr2.push(4); + +// arr2 става [1, 2, 3, 4] +// arr остава неафектиран +</pre> + +<div class="blockIndicator note"> +<p><strong>Забележка</strong>: Разпределящият синтаксис ефективно минава едно ниво по-дълбоко докато копира масив. Затова може да не е подходящ за копиране на многомерни масиви както показва следния пример(същото е с {{jsxref("Object.assign()")}} и разпределящ синтаксис).</p> +</div> + +<pre class="brush: js">var a = [[1], [2], [3]]; +var b = [...a]; +b.shift().shift(); // 1 +// Сега масивът a също е афектиран: [[], [2], [3]] +</pre> + +<h4 id="По-добър_начин_за_конкатениране_на_масиви">По-добър начин за конкатениране на масиви</h4> + +<p>{{jsxref("Array.prototype.concat()")}} често е използван за конкатениране на масив към края на вече съществуващ масив. Без използване на разпределящ синтаксис това може да бъде направено по следния начин:</p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +// Добавя всички елементи от arr2 след тези на arr1 +arr1 = arr1.concat(arr2);</pre> + +<p>С разпределящ синтаксис това има вида: </p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +arr1 = [...arr1, ...arr2]; // arr1 сега е [0, 1, 2, 3, 4, 5] +</pre> + +<p>{{jsxref("Array.prototype.unshift()")}} често се използва за добавяне на масив със стойности в началото на вече съществуващ масив. Без разпределящ синтаксис това може да бъде направено по следния начин: </p> + +<pre class="brush: js">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]</pre> + +<p>С разпределящ синтаксис става по следния начин: </p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +arr1 = [...arr2, ...arr1]; // arr1 сега е [3, 4, 5, 0, 1, 2] +</pre> + +<div class="blockIndicator note"> +<p><strong>Забележка: </strong>За разлика от <code>unshift()</code>, това създава нов <code>arr1</code>, а не модифицира оригиналния масив <code>arr1</code>. </p> +</div> + +<h3 id="Разпределящ_синтаксис_при_дефиниця_на_обекти">Разпределящ синтаксис при дефиниця на обекти</h3> + +<p>Предложението за <a href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> (етап 4) добавя разпределящи свойства към дефиницията на обекти. То копира собствени изброими свойства от даден обект към нов обект.</p> + +<p>Повърхностното клониране(изключващо prototype) или смесването на обекти вече е възможно с помощта на по-кратък синтаксис от {{jsxref("Object.assign()")}}.</p> + +<pre class="brush: js">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 }</pre> + +<p>Обърнете внимание, че {{jsxref("Object.assign()")}} извиква <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setters</a> за разлика от разпределящия синтаксис.</p> + +<p>Забележете, че функцията {{jsxref("Object.assign()")}} не може нито да бъде подменена, нито да се напише подобна:</p> + +<pre class="brush: js">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 } }</pre> + +<p>В горния пример разпределящият синтаксис не работи както се очаква: той разпределя масив от аргументи в дефиницията на обекта според зададените параметри. </p> + +<h3 id="Само_за_итериращи_променливи">Само за итериращи променливи</h3> + +<p>Разпределящият синтаксис (както и разпределящите свойства) може да бъде приложен само върху обекти, които могат да бъдат итерирани:</p> + +<pre class="brush: js">var obj = {'key1': 'value1'}; +var array = [...obj]; // TypeError: obj не може да се итерира +</pre> + +<h3 id="Разпределящ_синтаксис_с_много_стойности">Разпределящ синтаксис с много стойности </h3> + +<p>Когато използваме разпределящ синтаксис за извикване на функции трябва да бъдем запознати с възможността за надвишаване на лимита на брой на аргументи на функция в Javascript. За повече информация вижте {{jsxref("Function.prototype.apply", "apply()")}}.</p> + +<h2 id="Обединяващ_синтаксис_параметри">Обединяващ синтаксис (параметри) </h2> + +<p>Обединяващият синтаксис изглежда точно както разпределящия синтаксис, но е използван за разлагане на масиви и обекти. Иначе казано, обединяващият синтаксис е точно обратното на разпределящия синтаксис: докато разпределящият синтаксис разширява масива си със стойности, обединяващият синтаксис събира няколко елемента и ги събира в един елемент. За повече информация вижте <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters">rest parameters.</a></p> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#sec-array-initializer')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Дефинирана в няколко секции на спецификацията: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array-initializer">Array Initializer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-argument-lists">Argument Lists</a></td> + </tr> + <tr> + <td>{{SpecName('ES2018', '#sec-object-initializer')}}</td> + <td>{{Spec2('ES2018')}}</td> + <td>Дефинирана в <a href="http://www.ecma-international.org/ecma-262/9.0/#sec-object-initializer">Object Initializer</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Няма промени.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Няма промени.</td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_с_браузъри">Съвместимост с браузъри</h2> + + + +<p>{{Compat("javascript.operators.spread")}}</p> + +<h2 id="Вижте_още">Вижте още</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters">Rest parameters</a> (също ‘<code>...</code>’)</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">fn.apply</a> (също ‘<code>...</code>’)</li> +</ul> |
