diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
| commit | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (patch) | |
| tree | d4a40e13ceeb9f85479605110a76e7a4d5f3b56b /files/bg/web/javascript/reference/global_objects | |
| parent | 33058f2b292b3a581333bdfb21b8f671898c5060 (diff) | |
| download | translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.gz translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.bz2 translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.zip | |
initial commit
Diffstat (limited to 'files/bg/web/javascript/reference/global_objects')
5 files changed, 1146 insertions, 0 deletions
diff --git a/files/bg/web/javascript/reference/global_objects/array/index.html b/files/bg/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..1d2a114327 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,460 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>The JavaScript <strong><code>Array</code></strong> object is a global object that is used in the construction of arrays; which are high-level, list-like objects.</p> + +<p><strong>Create an Array</strong></p> + +<pre class="brush: js">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>Access (index into) an Array item</strong></p> + +<pre class="brush: js">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>Loop over an Array</strong></p> + +<pre class="brush: js">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>Add to the end of an Array</strong></p> + +<pre class="brush: js">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>Remove from the end of an Array</strong></p> + +<pre class="brush: js">var last = fruits.pop(); // remove Orange (from the end) +// ["Apple", "Banana"]; +</pre> + +<p><strong>Remove from the front of an Array</strong></p> + +<pre class="brush: js">var first = fruits.shift(); // remove Apple from the front +// ["Banana"]; +</pre> + +<p><strong>Add to the front of an Array</strong></p> + +<pre class="brush: js">var newLength = fruits.unshift('Strawberry') // add to the front +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>Find the index of an item in the Array</strong></p> + +<pre class="brush: js">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>Remove an item by index position</strong></p> + +<pre class="brush: js">var removedItem = fruits.splice(pos, 1); // this is how to remove an item + +// ["Strawberry", "Mango"]</pre> + +<p><strong>Remove items from an index position</strong></p> + +<pre class="brush: js">var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; +console.log(vegetables); +// ["Cabbage", "Turnip", "Radish", "Carrot"] + +var pos = 1, n = 2; + +var removedItems = vegetables.splice(pos, n); +// this is how to remove items, n defines the number of items to be removed, +// from that position(pos) onward to the end of array. + +console.log(vegetables); +// ["Cabbage", "Carrot"] (the original array is changed) + +console.log(removedItems); +// ["Turnip", "Radish"]</pre> + +<p><strong>Copy an Array</strong></p> + +<pre class="brush: js">var shallowCopy = fruits.slice(); // this is how to make a copy +// ["Strawberry", "Mango"] +</pre> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] +new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) +new Array(<var>arrayLength</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the <code>Array</code> constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the <code>Array</code> constructor, not array literals created with the bracket syntax.</dd> + <dt><code>arrayLength</code></dt> + <dd>If the only argument passed to the <code>Array</code> constructor is an integer between 0 and 2<sup>32</sup>-1 (inclusive), this returns a new JavaScript array with its <code>length</code> property set to that number (<strong>Note:</strong> this implies an array of <code>arrayLength</code> empty slots, not slots with actual <code>undefined</code> values). If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.</p> + +<p>Arrays cannot use strings as element indexes (as in an <a href="https://en.wikipedia.org/wiki/Associative_array">associative array</a>) but must use integers. Setting or accessing via non-integers using <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">bracket notation</a> (or <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">dot notation</a>) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's <a href="/en-US/docs/Web/JavaScript/Data_structures#Properties">object property collection</a>. The array's object properties and list of array elements are separate, and the array's <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_methods">traversal and mutation operations</a> cannot be applied to these named properties.</p> + +<h3 id="Accessing_array_elements">Accessing array elements</h3> + +<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1. Using an invalid index number returns <code>undefined</code>.</p> + +<pre class="brush: js">var arr = ['this is the first element', 'this is the second element', 'this is the last 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 last element' +</pre> + +<p>Array elements are object properties in the same way that <code>toString</code> is a property, but trying to access an element of an array as follows throws a syntax error because the property name is not valid:</p> + +<pre class="brush: js">console.log(arr.0); // a syntax error +</pre> + +<p>There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> + +<pre class="brush: js">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // a syntax error +console.log(years[0]); // works properly +</pre> + +<pre class="brush: js">renderer.3d.setTexture(model, 'character.png'); // a syntax error +renderer['3d'].setTexture(model, 'character.png'); // works properly +</pre> + +<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is, for this reason, that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> + +<pre class="brush: js">console.log(years['2'] != years['02']); +</pre> + +<p>Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation (but it can be accessed by dot notation in firefox 40.0a2 at least):</p> + +<pre class="brush: js">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['var']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> + +<p>A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join()")}}, {{jsxref("Array.slice", "slice()")}}, {{jsxref("Array.indexOf", "indexOf()")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push()")}}, {{jsxref("Array.splice", "splice()")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.</p> + +<pre class="brush: js">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:</p> + +<pre class="brush: js">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>Increasing the {{jsxref("Array.length", "length")}}.</p> + +<pre class="brush: js">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> + +<pre class="brush: js">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>This is explained further on the {{jsxref("Array.length")}} page.</p> + +<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> + +<p>The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:</p> + +<pre class="brush: js">// Match one d followed by one or more b's followed by one d +// Remember matched b's and the following d +// Ignore case + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>The properties and elements returned from this match are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Property/Element</td> + <td class="header">Description</td> + <td class="header">Example</td> + </tr> + <tr> + <td><code>input</code></td> + <td>A read-only property that reflects the original string against which the regular expression was matched.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>A read-only property that is the zero-based index of the match in the string.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>A read-only element that specifies the last matched characters.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Returns true if a variable is an array, if not false.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<div class="warning"> +<p><strong>Array generics are non-standard, deprecated and will get removed in the near future</strong>. </p> +</div> + +<p>Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> + +<p>These are <strong>not</strong> part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:</p> + +<pre class="brush: js">if (Array.from(str).every(isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_an_array">Creating an array</h3> + +<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> + +<pre class="brush: js">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 id="Creating_a_two-dimensional_array">Creating a two-dimensional array</h3> + +<p>The following creates a chess board as a two-dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.</p> + +<pre class="brush: js">var board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ]; + +console.log(board.join('\n') + '\n\n'); + +// Move King's Pawn forward 2 +board[4][4] = board[6][4]; +board[6][4] = ' '; +console.log(board.join('\n')); +</pre> + +<p>Here is the output:</p> + +<pre class="eval">R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , , , , , + , , , , , , , +p,p,p,p,p,p,p,p +r,n,b,q,k,b,n,r + +R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , ,p, , , + , , , , , , , +p,p,p,p, ,p,p,p +r,n,b,q,k,b,n,r +</pre> + +<h3 id="Using_an_array_to_tabulate_a_set_of_values">Using an array to tabulate a set of values</h3> + +<pre class="brush: js">values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</pre> + +<p>Results in</p> + +<pre class="eval">0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162</pre> + +<p>(First column is the (index))</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}</td> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> diff --git a/files/bg/web/javascript/reference/global_objects/array/splice/index.html b/files/bg/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..36d82dc700 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - JavaScript + - splice + - Масив + - заместване + - метод + - премахване +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +<div>{{JSRef}}</div> + +<p>Методът <strong><code>splice()</code></strong> променя съдържанието на масива като изтрива или заменя съществуващи елементи и/или добавя нови.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-splice.html")}}</div> + + + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox">let <var>arrDeletedItems</var> = <var>array</var>.splice(<var>start</var>[, <var>deleteCount</var>[, <var>item1</var>[, <var>item2</var>[, ...]]]]) +</pre> + +<h3 id="Параметри">Параметри</h3> + +<dl> + <dt><code><var>start</var></code></dt> + <dd>Индексът, от който започва промяната на масива.</dd> + <dd>Ако числото е по-голямо от дължината на масива, стойността на <code><var>start</var></code> ще се промени автоматично и ще приеме стойност равна на дължината на масива. В този случай няма да бъдат изтрити елементи от масива. Методът ще се държи като функция за добавяне на елементи и ще добави толкова елементи колкото са подадени като item[n*].</dd> + <dd>Ако <code><var>start</var></code> е отрицателно число обработката на масива ще започне от края на масива.( Случай че, <code><var>start</var></code> e -1 това означава -n е индексът на n-тия последен елемент и следователно е еквивалентен на <code>array.length - n</code> ).</dd> + <dd>Ако <code><var>array</var>.length + <var>start</var></code> е по-малко от <code>0</code>, ще започне от индекс <code>0</code>.</dd> + <dt><code><var>deleteCount</var></code> {{optional_inline}}</dt> + <dd>Число, което показва колко елемента трябва да бъдат изтрити ( започва се от <code><var>start</var></code> ).</dd> + <dd>If <code><var>deleteCount</var></code> is omitted, or if its value is equal to or larger than <code><var>array</var>.length - <var>start</var></code> (that is, if it is equal to or greater than the number of elements left in the array, starting at <code><var>start</var></code>), then all the elements from <code><var>start</var></code> to the end of the array will be deleted.</dd> + <dd> + <div class="blockIndicator note"> + <p><strong>Note:</strong> In IE8, it won't delete all when <code><var>deleteCount</var></code> is omitted.</p> + </div> + </dd> + <dd>If <code><var>deleteCount</var></code> is <code>0</code> or negative, no elements are removed. In this case, you should specify at least one new element (see below).</dd> + <dt><code><var>item1</var>, <var>item2</var>, ...</code> {{optional_inline}}</dt> + <dd>The elements to add to the array, beginning from <code><var>start</var></code>. If you do not specify any elements, <code>splice()</code> will only remove elements from the array.</dd> +</dl> + +<h3 id="Върната_стойност">Върната стойност</h3> + +<p>Методът връща масив, съдържащ изтритите елементи.</p> + +<p>Ако само един елемент е премахнат, резултатът ще бъде масив с един елемент.</p> + +<p>Ако няма изтрити елементи, резултатът ще бъде празен масив.</p> + +<h2 id="Описание">Описание</h2> + +<p>Ако броя на добавените елементи се различава от броя на изтритите, ще има промяна в дължината на масива.</p> + +<h2 id="Примери">Примери</h2> + +<h3 id="Премахват_се_0_елемента_пред_индекс_2_и_се_добавя_drum">Премахват се 0 елемента пред индекс 2 и се добавя "drum"</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'] +// Ако изходният ви код е в utf8, можете да ползвате всякакви азбуки +let премахнат = myFish.splice(2, 0, 'drum') + +// myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"] +// премахнат = [], не са премахнати елементи</pre> + +<h3 id="Премахват_се_0_елемента_пред_индекс_2_и_се_добавят_drum_и_guitar">Премахват се 0 елемента пред индекс 2 и се добавят "drum" и "guitar"</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'] +let removed = myFish.splice(2, 0, 'drum', 'guitar') + +// myFish = ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] +// removed = [], не са премахнати елементи +</pre> + +<h3 id="Премахва_се_един_елемент_започвайки_от_индекс_3">Премахва се един елемент, започвайки от индекс 3</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'] +let removed = myFish.splice(3, 1) + +// removed = ["mandarin"] +// myFish = ["angel", "clown", "drum", "sturgeon"] +</pre> + +<h3 id="Remove_1_element_at_index_2_and_insert_trumpet">Remove 1 element at index 2, and insert "trumpet"</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'drum', 'sturgeon'] +let removed = myFish.splice(2, 1, 'trumpet') + +// myFish = ["angel", "clown", "trumpet", "sturgeon"] +// removed = ["drum"]</pre> + +<h3 id="Remove_2_elements_from_index_0_and_insert_parrot_anemone_and_blue">Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'trumpet', 'sturgeon'] +let removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue') + +// myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"] +// removed = ["angel", "clown"]</pre> + +<h3 id="Remove_2_elements_from_index_2">Remove 2 elements from index 2</h3> + +<pre class="brush: js">let myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'] +let removed = myFish.splice(2, 2) + +// myFish = ["parrot", "anemone", "sturgeon"] +// removed = ["blue", "trumpet"]</pre> + +<h3 id="Remove_1_element_from_index_-2">Remove 1 element from index -2</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'] +let removed = myFish.splice(-2, 1) + +// myFish = ["angel", "clown", "sturgeon"] +// removed = ["mandarin"]</pre> + +<h3 id="Remove_all_elements_after_index_2_incl.">Remove all elements after index 2 (incl.)</h3> + +<pre class="brush: js">let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'] +let removed = myFish.splice(2) + +// myFish = ["angel", "clown"] +// removed = ["mandarin", "sturgeon"]</pre> + +<h2 id="Спецификация">Спецификация</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_и_подръжка">Съвместимост и подръжка</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.splice")}}</p> +</div> + +<h2 id="Виж_повече">Виж повече</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}}— добавя/премахва елемент от края на масива</li> + <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}}— добавя/премахва елемент от началото на масива</li> + <li>{{jsxref("Array.prototype.concat()", "concat()")}}— връща нов масив състоящ се от този масив, обединен с друг масив или стойности.</li> +</ul> diff --git a/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html b/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..6849a4d7b2 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,96 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<div></div> + +<p><strong><code>ArrayBuffer</code></strong> обекта се използва за репрезентиране на най общ бъфер за двоични данни със статична дължина.</p> + +<p>Това е масив от байтове, често наричан в други езици "byte array".Не можете директно да манипулирате съдържанието на <code>ArrayBuffer</code>; вместо това вие трябва да създадете <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">масив от типизирани обекти</a> или {{jsxref("DataView")}} обект, който ще представлява бъфера в специфичен формат, който ще се използва за да чете съдържанието на бъфера.</p> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer">ArrayBuffer()</a></code> конструктора създава нов <code>ArrayBuffer</code> от подадена дължина в байтове, можете също да получите <code>ArrayBuffer</code> от вече съществуващи данни, например <a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix_to_Solution_1_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">от Base64 низ</a> или от <a href="/en-US/docs/Web/API/FileReader/readAsArrayBuffer">файл от вашата система</a>.</p> + +<h2 id="Конструктор">Конструктор</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}}</dt> + <dd>Създава нови <code>ArrayBuffer</code> обекти.</dd> +</dl> + +<h2 id="Свойства">Свойства</h2> + +<dl> + <dt><code>ArrayBuffer.length</code> </dt> + <dd>Връща броя параметри на конструктор функцията на <code>ArrayBuffer</code> , който е 1.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>Конструктор функцията, която се използва за създаване на нови обекти.</dd> + <dt><code>ArrayBuffer.prototype</code></dt> + <dd>Позволява за добавянето на допълнителни свойства към всички <code>ArrayBuffer</code> обекти.</dd> +</dl> + +<h2 id="Методи">Методи</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Връща <code>true</code> ако <code>arg</code> е един от буферните масивни типове, като <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">масив от типизирани обекти</a> или {{jsxref("DataView")}}. Връща <code>false</code> в противен случай.</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}}</dt> + <dd> + <div class="line" id="file-arraybuffer-transfer-LC6">Връща нов <code>ArrayBuffer</code> ,чието съдържание е взето от данните на <code>oldBuffer</code> и след това се скъсява или се доплъват водещите нули (zero-extended) с <code>newByteLength</code>.</div> + </dd> +</dl> + +<h2 id="Инстанции">Инстанции</h2> + +<p>Всички <code>ArrayBuffer</code> инстанции наследяват <code>ArrayBuffer.prototype</code>.</p> + +<h3 id="Свойства_2">Свойства</h3> + +<dl> + <dt><code>ArrayBuffer.prototype.constructor</code></dt> + <dd>Е функцията, която създава прототипа на обекта. Началната стойност е стандартният, вграден конструктор на <code>ArrayBuffer</code>.</dd> + <dt>{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd>Големината, в байтове на <code>ArrayBuffer</code>. Това се установява когато масива се създава и не може да се променя.</dd> +</dl> + +<h3 id="Методи_2">Методи</h3> + +<dl> + <dt>{{jsxref("ArrayBuffer.prototype.slice()")}}</dt> + <dd>Връща нов <code>ArrayBuffer</code>, чието съдържание е копие на байтовете на този <code>ArrayBuffer</code> от <code>begin(началото)</code>, включително, до <code>end(края)</code>, изключае.Ако някое от <code>begin</code> или <code>end</code> е отрицателно, се отнася към индекс в края на масива, вместо в началото.</dd> +</dl> + +<h2 id="Пример">Пример</h2> + +<p>В този пример ще създадем 8-битов бъфер с {{jsxref("Int32Array")}} изглед, рефериращ към бъфера:</p> + +<pre class="brush: js">const buffer = new ArrayBuffer(8); +const view = new Int32Array(buffer);</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Спецификация</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-objects', 'ArrayBuffer')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_на_браузъра">Съвместимост на браузъра</h2> + +<div class="hidden">Таблицата за съвемстимост се генерира от структурни данни. Ако искате да допринесете към данните, моля вижте <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> и ни изпратете pull request.</div> + +<p>{{Compat("javascript.builtins.ArrayBuffer")}}</p> + +<h2 id="Вижте_също">Вижте също</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/bg/web/javascript/reference/global_objects/index.html b/files/bg/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..6af3563dd3 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/index.html @@ -0,0 +1,182 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<p>{{JSSidebar("Objects")}}</p> + +<p>This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.</p> + +<p>The term "global objects" (or standard built-in objects) here is not to be confused with the <strong>global object</strong>. Here, global objects refer to <strong>objects in the global scope</strong>. The <strong>global object</strong> itself can be accessed using the {{JSxRef("Operators/this", "this")}} operator in the global scope (but only if ECMAScript 5 strict mode is not used; in that case it returns {{JSxRef("undefined")}}). In fact, the global scope <strong>consists of</strong> the properties of the global object, including inherited properties, if any.</p> + +<p>Other objects in the global scope are either <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">created by the user script</a> or provided by the host application. The host objects available in browser contexts are documented in the <a href="/en-US/docs/Web/API/Reference">API reference</a>. For more information about the distinction between the <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> and core <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h2 id="Standard_objects_by_category">Standard objects by category</h2> + +<h3 id="Value_properties">Value properties</h3> + +<p>These global properties return a simple value; they have no properties or methods.</p> + +<ul> + <li>{{JSxRef("Infinity")}}</li> + <li>{{JSxRef("NaN")}}</li> + <li>{{JSxRef("undefined")}}</li> + <li>{{JSxRef("null")}} literal</li> + <li>{{JSxRef("globalThis")}}</li> +</ul> + +<h3 id="Function_properties">Function properties</h3> + +<p>These global functions—functions which are called globally rather than on an object—directly return their results to the caller.</p> + +<ul> + <li>{{JSxRef("Global_Objects/eval", "eval()")}}</li> + <li>{{JSxRef("Global_Objects/uneval", "uneval()")}} {{Non-standard_Inline}}</li> + <li>{{JSxRef("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{JSxRef("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{JSxRef("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{JSxRef("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{JSxRef("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{JSxRef("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{JSxRef("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{JSxRef("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{JSxRef("Global_Objects/escape", "escape()")}} {{Deprecated_Inline}}</li> + <li>{{JSxRef("Global_Objects/unescape", "unescape()")}} {{Deprecated_Inline}}</li> +</ul> + +<h3 id="Fundamental_objects">Fundamental objects</h3> + +<p>These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.</p> + +<ul> + <li>{{JSxRef("Object")}}</li> + <li>{{JSxRef("Function")}}</li> + <li>{{JSxRef("Boolean")}}</li> + <li>{{JSxRef("Symbol")}}</li> + <li>{{JSxRef("Error")}}</li> + <li>{{JSxRef("EvalError")}}</li> + <li>{{JSxRef("InternalError")}} {{Non-standard_Inline}}</li> + <li>{{JSxRef("RangeError")}}</li> + <li>{{JSxRef("ReferenceError")}}</li> + <li>{{JSxRef("SyntaxError")}}</li> + <li>{{JSxRef("TypeError")}}</li> + <li>{{JSxRef("URIError")}}</li> +</ul> + +<h3 id="Numbers_and_dates">Numbers and dates</h3> + +<p>These are the base objects representing numbers, dates, and mathematical calculations.</p> + +<ul> + <li>{{JSxRef("Number")}}</li> + <li>{{JSxRef("BigInt")}}</li> + <li>{{JSxRef("Math")}}</li> + <li>{{JSxRef("Date")}}</li> +</ul> + +<h3 id="Text_processing">Text processing</h3> + +<p>These objects represent strings and support manipulating them.</p> + +<ul> + <li>{{JSxRef("String")}}</li> + <li>{{JSxRef("RegExp")}}</li> +</ul> + +<h3 id="Indexed_collections">Indexed collections</h3> + +<p>These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.</p> + +<ul> + <li>{{JSxRef("Array")}}</li> + <li>{{JSxRef("Int8Array")}}</li> + <li>{{JSxRef("Uint8Array")}}</li> + <li>{{JSxRef("Uint8ClampedArray")}}</li> + <li>{{JSxRef("Int16Array")}}</li> + <li>{{JSxRef("Uint16Array")}}</li> + <li>{{JSxRef("Int32Array")}}</li> + <li>{{JSxRef("Uint32Array")}}</li> + <li>{{JSxRef("Float32Array")}}</li> + <li>{{JSxRef("Float64Array")}}</li> + <li>{{JSxRef("BigInt64Array")}}</li> + <li>{{JSxRef("BigUint64Array")}}</li> +</ul> + +<h3 id="Keyed_collections">Keyed collections</h3> + +<p>These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.</p> + +<ul> + <li>{{JSxRef("Map")}}</li> + <li>{{JSxRef("Set")}}</li> + <li>{{JSxRef("WeakMap")}}</li> + <li>{{JSxRef("WeakSet")}}</li> +</ul> + +<h3 id="Structured_data">Structured data</h3> + +<p>These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).</p> + +<ul> + <li>{{JSxRef("ArrayBuffer")}}</li> + <li>{{JSxRef("SharedArrayBuffer")}} {{Experimental_Inline}}</li> + <li>{{JSxRef("Atomics")}} {{Experimental_Inline}}</li> + <li>{{JSxRef("DataView")}}</li> + <li>{{JSxRef("JSON")}}</li> +</ul> + +<h3 id="Control_abstraction_objects">Control abstraction objects</h3> + +<ul> + <li>{{JSxRef("Promise")}}</li> + <li>{{JSxRef("Generator")}}</li> + <li>{{JSxRef("GeneratorFunction")}}</li> + <li>{{JSxRef("AsyncFunction")}} {{Experimental_Inline}}</li> +</ul> + +<h3 id="Reflection">Reflection</h3> + +<ul> + <li>{{JSxRef("Reflect")}}</li> + <li>{{JSxRef("Proxy")}}</li> +</ul> + +<h3 id="Internationalization">Internationalization</h3> + +<p>Additions to the ECMAScript core for language-sensitive functionalities.</p> + +<ul> + <li>{{JSxRef("Intl")}}</li> + <li>{{JSxRef("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}</li> + <li>{{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> + <li>{{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}</li> + <li>{{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/Locale", "Intl.Locale")}}</li> +</ul> + +<h3 id="WebAssembly">WebAssembly</h3> + +<ul> + <li>{{JSxRef("WebAssembly")}}</li> + <li>{{JSxRef("WebAssembly.Module")}}</li> + <li>{{JSxRef("WebAssembly.Instance")}}</li> + <li>{{JSxRef("WebAssembly.Memory")}}</li> + <li>{{JSxRef("WebAssembly.Table")}}</li> + <li>{{JSxRef("WebAssembly.CompileError")}}</li> + <li>{{JSxRef("WebAssembly.LinkError")}}</li> + <li>{{JSxRef("WebAssembly.RuntimeError")}}</li> +</ul> + +<h3 id="Other">Other</h3> + +<ul> + <li>{{JSxRef("Functions/arguments", "arguments")}}</li> +</ul> diff --git a/files/bg/web/javascript/reference/global_objects/promise/index.html b/files/bg/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..3145756561 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,253 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - JavaScript + - Promises + - Refere +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise</code></strong> обектът представлява евентуалният завършек (или неуспех) на една асинхронна операция и нейната получена стойност.</p> + +<div class="note"> +<p><strong>Бележка:</strong> Тази статия описва <code>Promise</code> конструктора и методите и свойствата на такива обекти. За да научите начина по който работят <code>promises</code>и как може да ги използвате , съветваме ви първо да прочетете <a href="/docs/Web/JavaScript/Guide/Using_promises">Как да използваме promises. </a>Конструктора се използва предимно за обхващане на функции, които вече не поддържат <code>promises</code></p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox">new Promise(<var>executor</var>);</pre> + +<h3 id="Параметри">Параметри</h3> + +<dl> + <dt><code>екзекутор (executor)</code></dt> + <dd>Функция , която се предава с аргументи <code>resolve</code> и <code>reject</code>. Екзекутор (<code>executor</code>) функцията се изпълнява незабавно след изпълнението на <code>Promise</code>, предава <code>resolve</code> и <code>reject</code> функции (Екзекутора (<code>executor</code>) се извиква преди <code>Promise</code> конструктора , дори връща създадения обект). <code>resolve</code> и <code>reject</code> функциите, когато се извикват, разрешават или отхвърлят съответния <code>promise</code>. Екзекутора (<code>executor</code>) обикновено инициира някаква асинхронна работа и след като веднъж приключи, извиква <code>resolve</code> функцията, за да разреши <code>promise</code> или дори да го отхвъли ако възникне грешка. Ако възникне грешка в екзекутора (<code>executor</code>) , <code>promise</code> се отхвърля и върнатата стойност от екзекутора (<code>executor</code>) се отхвърля.</dd> +</dl> + +<h2 id="Описание">Описание</h2> + +<p><code><strong>Promise</strong></code> е прокси за стойността, която не е непременно известна , когато се създава <code>promise</code>. Позволява ви да свържете манипулаторите с асинхронно действие, евентуално връщайки успешна стойност или грешка. Това позволява асинхронните методи да връщат стойност като синхронни методи: вместо да ни върне незабавно финална стойност, асинхронния метод връща <em>promise</em>, който да ни предостави стойността в някакъв бъдещ момент.</p> + +<p><code>Promise</code> се намира в едно от тези състояния:</p> + +<ul> + <li><em>pending (изчакващо)</em>: първоначално състояние, нито изпълнено или отхвърлено.</li> + <li><em>fulfilled</em> (изпълнено): означава , че операцията е завършила успешно.</li> + <li><em>rejected (отказано)</em>: означава , че операцията не е завършила успешно.</li> +</ul> + +<p>Изчакващият promise може да бъде изпълнен със стойност или отказан с описание за грешка. Когато някоя от тези опции се случи, се извикват асоциираните манипулатори, поставени на опашка, след което се извикват <code>then</code> методите. (Ако promise вече е бил изпълнен или отказан, когато е приложен съответния манипулатор , манипулатора ще бъде извикан. Така че няма никакво състезателно условие между завършването на асинхронната операция и манипулаторите които са и били приложени.)</p> + +<p>Като <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> и <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> методи връщат promises, те могат да бъдат обхванати.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15911/promises.png" style="height: 297px; width: 801px;"></p> + +<div class="note"> +<p><strong>Забележка, не трябва да се бърка с:</strong> Няколко дргуи езика имат механизъм за мързеливо (lazy) оценяване и отлагане на изчисления, които те също наричат "promises" ... схема. Promises в JavaScript представляват процеси, които вече се случват и могат да бъдат обхванати с функции за обратно извикване (callback functions). Ако търсите мързеливо да изчислите израз, разгледайте <a href="/docs/Web/JavaScript/Reference/Functions/Arrow_functions">функциите със стрелка (arrow function)</a> без аргументи: <code>f = () => <em>израз(expression)</em></code> за създаване на мързеливо-изчислителен израз и <code>f()</code> за изчисление.</p> +</div> + +<div class="note"> +<p><strong>Забележка</strong>: Казва се че Promise се счита за <em>установен</em> ако е изпълнен или отказан, но не изчакващ. Също така ще чуете и термина <em>resolved</em>, който се изпозлва с promises — това означава че promise е установен или “заключен”, изчаквайки да съответства на състоянието на друг promise. <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> съдържа повече детайли относно promise терминологията.</p> +</div> + +<h2 id="Свойства">Свойства</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>Дължина на свойство, чиято дължина е винаги 1 (номер на аругмента на конструктора).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd>Представялва прототипа на <code>Promise</code> конструктора.</dd> +</dl> + +<h2 id="Методи">Методи</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd>Изчаква всички promises да бъдат разрешени или отказани.</dd> + <dd>Ако върнатия promise е решен(resolves), той се решава с агрегиращ масив от стойности от разрешените promises в същата последователност, както е дефиниран в многобройните promises. Ако е отхвърлен, той се отхвърля с причина от първият promise който е бил отказан.</dd> + <dt>{{jsxref("Promise.allSettled", "Promise.allSettled()")}}</dt> + <dd>Изчаква докато всички promises са приключени/уредени (всеки може да бъде разрешен или отказан).</dd> + <dd>Връща promise което се решава след всички дадени promises били те разрешени или отказани, с масив от обекти , които описват резултата от всеки promise.</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd>Изчаква докато някой от promises е разрешен или отказан.</dd> + <dd>Ако върнатият promise е разрешен,е разрешен със стойноста от първият promise.Ако е отказан, е отакзан с причината от първият promise който е бил отказан.</dd> + <dt>{{jsxref("Promise.reject", "Promise.reject()")}}</dt> + <dd>Връща нов <code>Promise</code> обект, който е отказан с предоставена причина.</dd> + <dt>{{jsxref("Promise.resolve", "Promise.resolve()")}}</dt> + <dd>Връща нов <code>Promise</code> който е разрешен с дадената му стойност. Ако стойността е thenable (i.e. има <code>then</code> метод), върнатият promise ще "следва" този thenable, приемайки евентуалното му състояние; в противен случай върнатия promise ще бъде запълнен със стойността. Обикновенно ако не знаете дадена стойност дали е promise или не, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} замества и работи с върнатата стойност като promise.</dd> +</dl> + +<h2 id="Promise_прототип">Promise прототип</h2> + +<h3 id="Свойства_2">Свойства</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> + +<h3 id="Методи_2">Методи</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> + +<h2 id="Създаване_на_Promise">Създаване на Promise</h2> + +<p><code>Promise</code> се създава, използвайки ключовата дума <code>new</code> и нейният конструктор. Този конструктор приема като аргумент функция, наричаща се "executor function". Тази функция трябва да приеме две функции като параметри. Първата от тези функции (<code>resolve</code>) се извиква когато асинхронната задача завърши успешно и върне резултата от задачата като стойност. Вторият (<code>reject</code>) се извиква когато задачата се провали и връща причината за този провал, който обикновенно е обект съдържайки в себе си грешката.</p> + +<pre class="brush: js">const myFirstPromise = new Promise((resolve, reject) => { + // do something asynchronous which eventually calls either: + // + // resolve(someValue); // fulfilled + // or + // reject("failure reason"); // rejected +}); +</pre> + +<p>За да предоставите функция с promise функционалност, просто върнете promise:</p> + +<pre class="brush: js">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(); + }); +}</pre> + +<h2 id="Примери">Примери</h2> + +<h3 id="Основни_примери">Основни примери</h3> + +<pre class="brush: js">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); +}); +</pre> + +<h3 id="Разширени_примери">Разширени примери</h3> + +<pre class="brush: html hidden"><button id="btn">Make a promise!</button> +<div id="log"></div> +</pre> + +<p>Този малък пример показва механизма на <code>Promise</code>. <code>testPromise()</code> метод се извиква всеки път когато {{HTMLElement("button")}} е натиснат. Създава promise който ще бъде изпълнен, използвайки {{domxref("window.setTimeout()")}}, към promise броенето(номер започващ от 1) на всеки 1-3 секунди на случаен принцип. The <code>Promise()</code> се използва за създаването на promise.</p> + +<p>Изпълнението на promise е просто записано, чрез сет за обратно извикване (callback set) , използвайки {{jsxref("Promise.prototype.then()","p1.then()")}}. <span lang="bg">Няколко logs (данни) показват как синхронната част на метода е отделена от асинхронното завършване на обещанието.</span></p> + +<pre class="brush: js">'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/>'); +}</pre> + +<pre class="brush:js hidden">if ("Promise" in window) { + let btn = document.getElementById("btn"); + btn.addEventListener("click",testPromise); +} else { + log = document.getElementById('log'); + log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; +} +</pre> + +<p>Този пример ще се стартира като кликнете на бутона. Имате нужда от браузер който поддържа <code>Promise</code>. Натискайки на бутона няколко пъти в кратки периоди от време , ще видите дори разллични promises , които се изпълняват един след друг.</p> + +<p>{{EmbedLiveSample("Advanced_Example", "500", "200")}}</p> + +<h2 id="Зареждане_на_снимка_с_XHR">Зареждане на снимка с XHR</h2> + +<p>Друг опростен пример използва <code>Promise</code> и {{domxref("XMLHttpRequest")}} за зареждане на снимки е наличен в GitHub профила на MDN и се казва <a href="https://github.com/mdn/js-examples/tree/master/promises-test">js-examples</a>. Тук също може да го видите и в действие <a href="https://mdn.github.io/js-examples/promises-test/">see it in action</a>. Всяка стъпка е коментирана и ви позволява да следвате Promise и XHR архитектурата внимателно.</p> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_с_браузърите">Съвместимост с браузърите</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Using_promises">Using promises</a></li> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> + <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> + <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> + <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> + <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> + <li><a href="https://www.udacity.com/course/javascript-promises--ud898">Udacity: JavaScript Promises</a></li> +</ul> |
