From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../reference/global_objects/array/index.html | 460 +++++++++++++++++++++ .../global_objects/array/splice/index.html | 155 +++++++ .../global_objects/arraybuffer/index.html | 96 +++++ .../javascript/reference/global_objects/index.html | 182 ++++++++ .../reference/global_objects/promise/index.html | 253 ++++++++++++ 5 files changed, 1146 insertions(+) create mode 100644 files/bg/web/javascript/reference/global_objects/array/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/promise/index.html (limited to 'files/bg/web/javascript/reference/global_objects') 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 +--- +
{{JSRef}}
+ +

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

+ +

Create an Array

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

Access (index into) an Array item

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

Loop over an Array

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

Add to the end of an Array

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

Remove from the end of an Array

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

Remove from the front of an Array

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

Add to the front of an Array

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

Find the index of an item in the Array

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

Remove an item by index position

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

Remove items from an index position

+ +
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"]
+ +

Copy an Array

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

Syntax

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

Parameters

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

Description

+ +

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

+ +

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

+ +

Accessing array elements

+ +

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

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

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

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

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

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

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

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

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

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

Relationship between length and numerical properties

+ +

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

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

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

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

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

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

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

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

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

+ +

Creating an array using the result of a match

+ +

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

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

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

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

Properties

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

Methods

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

Array instances

+ +

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

+ +

Properties

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

Methods

+ +

Mutator methods

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

Accessor methods

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

Iteration methods

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

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed in the near future

+
+ +

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

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

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

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

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

+ +

These are not part of ECMAScript standards 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:

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

Examples

+ +

Creating an array

+ +

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

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

Creating a two-dimensional array

+ +

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

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

Here is the output:

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

Using an array to tabulate a set of values

+ +
values = [];
+for (var x = 0; x < 10; x++){
+ values.push([
+  2 ** x,
+  2 * x ** 2
+ ])
+};
+console.table(values)
+ +

Results in

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

(First column is the (index))

+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Методът splice() променя съдържанието на масива като изтрива или заменя съществуващи елементи и/или добавя нови.

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

Синтаксис

+ +
let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

Параметри

+ +
+
start
+
Индексът, от който започва промяната на масива.
+
Ако числото е по-голямо от дължината на масива, стойността на start ще се промени автоматично и ще приеме стойност равна на дължината на масива. В този случай няма да бъдат изтрити елементи от масива. Методът ще се държи като функция за добавяне на елементи и ще добави толкова елементи колкото са подадени като item[n*].
+
Ако start е отрицателно число обработката на масива ще започне от края на масива.( Случай че, start e -1 това означава -n е индексът на n-тия последен елемент и следователно е еквивалентен на array.length - n ).
+
Ако array.length + start е по-малко от 0, ще започне от индекс 0.
+
deleteCount {{optional_inline}}
+
Число, което показва колко елемента трябва да бъдат изтрити ( започва се от start ).
+
If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.
+
+
+

Note: In IE8, it won't delete all when deleteCount is omitted.

+
+
+
If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).
+
item1, item2, ... {{optional_inline}}
+
The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.
+
+ +

Върната стойност

+ +

Методът връща масив, съдържащ изтритите елементи.

+ +

Ако само един елемент е премахнат, резултатът ще бъде масив с един елемент.

+ +

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

+ +

Описание

+ +

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

+ +

Примери

+ +

Премахват се 0 елемента пред индекс 2 и се добавя "drum"

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+// Ако изходният ви код е в utf8, можете да ползвате всякакви азбуки
+let премахнат = myFish.splice(2, 0, 'drum')
+
+// myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// премахнат = [], не са премахнати елементи
+ +

Премахват се 0 елемента пред индекс 2 и се добавят "drum" и "guitar"

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(2, 0, 'drum', 'guitar')
+
+// myFish = ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
+// removed = [], не са премахнати елементи
+
+ +

Премахва се един елемент, започвайки от индекс 3

+ +
let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
+let removed = myFish.splice(3, 1)
+
+// removed = ["mandarin"]
+// myFish = ["angel", "clown", "drum", "sturgeon"]
+
+ +

Remove 1 element at index 2, and insert "trumpet"

+ +
let myFish = ['angel', 'clown', 'drum', 'sturgeon']
+let removed = myFish.splice(2, 1, 'trumpet')
+
+// myFish = ["angel", "clown", "trumpet", "sturgeon"]
+// removed = ["drum"]
+ +

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

+ +
let myFish = ['angel', 'clown', 'trumpet', 'sturgeon']
+let removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue')
+
+// myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed = ["angel", "clown"]
+ +

Remove 2 elements from index 2

+ +
let myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']
+let removed = myFish.splice(2, 2)
+
+// myFish = ["parrot", "anemone", "sturgeon"]
+// removed = ["blue", "trumpet"]
+ +

Remove 1 element from index -2

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(-2, 1)
+
+// myFish = ["angel", "clown", "sturgeon"]
+// removed = ["mandarin"]
+ +

Remove all elements after index 2 (incl.)

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(2)
+
+// myFish = ["angel", "clown"]
+// removed = ["mandarin", "sturgeon"]
+ +

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

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}
+ +

Съвместимост и подръжка

+ +
+ + +

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

+
+ +

Виж повече

+ + 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 +--- +
{{JSRef}}
+ +
+ +

ArrayBuffer обекта се използва за репрезентиране на най общ бъфер за двоични данни със статична дължина.

+ +

Това е масив от байтове, често наричан в други езици "byte array".Не можете директно да манипулирате съдържанието на ArrayBuffer; вместо това вие трябва да създадете масив от типизирани обекти или {{jsxref("DataView")}} обект, който ще представлява бъфера в специфичен формат, който ще се използва за да чете съдържанието на бъфера.

+ +

ArrayBuffer() конструктора създава нов ArrayBuffer от подадена дължина в байтове, можете също да получите ArrayBuffer от вече съществуващи данни, например от Base64 низ или от файл от вашата система.

+ +

Конструктор

+ +
+
{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}}
+
Създава нови ArrayBuffer обекти.
+
+ +

Свойства

+ +
+
ArrayBuffer.length 
+
Връща броя параметри на конструктор функцията на ArrayBuffer , който е 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
Конструктор функцията, която се използва за създаване на нови обекти.
+
ArrayBuffer.prototype
+
Позволява за добавянето на допълнителни свойства към всички ArrayBuffer обекти.
+
+ +

Методи

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Връща true ако arg е един от буферните масивни типове, като масив от типизирани обекти или {{jsxref("DataView")}}. Връща false в противен случай.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}}
+
+
Връща нов ArrayBuffer ,чието съдържание е взето от данните на oldBuffer и след това се скъсява или се доплъват водещите нули (zero-extended) с newByteLength.
+
+
+ +

Инстанции

+ +

Всички ArrayBuffer инстанции наследяват ArrayBuffer.prototype.

+ +

Свойства

+ +
+
ArrayBuffer.prototype.constructor
+
Е функцията, която създава прототипа на обекта. Началната стойност е стандартният, вграден конструктор на ArrayBuffer.
+
{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
+
Големината, в байтове на ArrayBuffer. Това се установява когато масива се създава и не може да се променя.
+
+ +

Методи

+ +
+
{{jsxref("ArrayBuffer.prototype.slice()")}}
+
Връща нов ArrayBuffer, чието съдържание е копие на байтовете на този ArrayBuffer от begin(началото), включително, до end(края), изключае.Ако някое от begin или end е отрицателно, се отнася към индекс в края на масива, вместо в началото.
+
+ +

Пример

+ +

В този пример ще създадем 8-битов бъфер с {{jsxref("Int32Array")}}  изглед, рефериращ към бъфера:

+ +
const buffer = new ArrayBuffer(8);
+const view = new Int32Array(buffer);
+ +

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

+ + + + + + + + + + +
Спецификация
{{SpecName('ESDraft', '#sec-arraybuffer-objects', 'ArrayBuffer')}}
+ +

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

+ + + +

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

+ +

Вижте също

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

{{JSSidebar("Objects")}}

+ +

This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.

+ +

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope. The global object 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 consists of the properties of the global object, including inherited properties, if any.

+ +

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

+ +

Standard objects by category

+ +

Value properties

+ +

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

+ + + +

Function properties

+ +

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

+ + + +

Fundamental objects

+ +

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

+ + + +

Numbers and dates

+ +

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

+ + + +

Text processing

+ +

These objects represent strings and support manipulating them.

+ + + +

Indexed collections

+ +

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

+ + + +

Keyed collections

+ +

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

+ + + +

Structured data

+ +

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

+ + + +

Control abstraction objects

+ + + +

Reflection

+ + + +

Internationalization

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

WebAssembly

+ + + +

Other

+ + 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 +--- +
{{JSRef}}
+ +

Promise обектът представлява евентуалният завършек (или неуспех) на една асинхронна операция и нейната получена стойност.

+ +
+

Бележка:  Тази статия описва Promise конструктора и методите и свойствата на такива обекти. За да научите начина по който работят promisesи как може да ги използвате , съветваме ви първо да прочетете Как да използваме promises.  Конструктора се използва предимно за обхващане на функции, които вече не поддържат promises

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

Синтаксис

+ +
new Promise(executor);
+ +

Параметри

+ +
+
екзекутор (executor)
+
Функция , която се предава с аргументи resolve и reject. Екзекутор (executor) функцията се изпълнява незабавно след  изпълнението на Promise, предава resolve и reject функции (Екзекутора (executor) се извиква преди Promise конструктора , дори връща създадения обект). resolve и reject функциите, когато се извикват, разрешават или отхвърлят съответния  promise. Екзекутора (executor) обикновено инициира някаква асинхронна работа и след като веднъж приключи, извиква resolve функцията, за да разреши promise или дори да го отхвъли ако възникне грешка. Ако възникне грешка в екзекутора (executor) , promise  се отхвърля и върнатата стойност от екзекутора (executor) се отхвърля.
+
+ +

Описание

+ +

Promise е прокси за стойността, която не е непременно известна , когато се създава promise. Позволява ви да свържете манипулаторите с асинхронно действие, евентуално връщайки успешна стойност или грешка. Това позволява асинхронните методи да връщат стойност като синхронни методи: вместо да ни върне незабавно финална стойност, асинхронния метод връща promise, който да ни предостави стойността в някакъв бъдещ момент.

+ +

Promise се намира в едно от тези състояния:

+ + + +

Изчакващият promise може да бъде изпълнен със стойност или отказан с описание за грешка. Когато някоя от тези опции се случи, се извикват асоциираните манипулатори, поставени на опашка, след което се извикват then методите. (Ако promise вече е бил изпълнен или отказан, когато е приложен съответния манипулатор , манипулатора ще бъде извикан. Така че няма никакво състезателно условие между завършването на асинхронната операция и манипулаторите които са и били приложени.)

+ +

Като {{jsxref("Promise.then", "Promise.prototype.then()")}} и {{jsxref("Promise.catch", "Promise.prototype.catch()")}} методи връщат promises, те могат да бъдат обхванати.

+ +

+ +
+

Забележка, не трябва да се бърка с:  Няколко дргуи езика имат механизъм за мързеливо (lazy) оценяване и отлагане на изчисления, които те също наричат "promises" ... схема. Promises в JavaScript представляват процеси, които вече се случват и могат да бъдат обхванати с функции за обратно извикване (callback functions).  Ако търсите мързеливо да изчислите израз, разгледайте функциите със стрелка (arrow function) без аргументи: f = () => израз(expression) за създаване на мързеливо-изчислителен израз  и f() за изчисление.

+
+ +
+

Забележка: Казва се че Promise се счита за установен ако е изпълнен или отказан, но не изчакващ. Също така ще чуете и термина resolved, който се изпозлва с promises — това означава че promise е установен или “заключен”, изчаквайки да съответства на състоянието на друг promise. States and fates съдържа повече детайли относно promise терминологията.

+
+ +

Свойства

+ +
+
Promise.length
+
Дължина на свойство, чиято дължина е винаги 1 (номер на аругмента на конструктора).
+
{{jsxref("Promise.prototype")}}
+
Представялва прототипа на Promise конструктора.
+
+ +

Методи

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Изчаква всички promises да бъдат разрешени или отказани.
+
Ако върнатия promise е решен(resolves), той се решава с агрегиращ масив от стойности от разрешените promises в същата последователност, както е дефиниран в многобройните promises. Ако е отхвърлен, той се отхвърля с причина от първият promise който е бил отказан.
+
{{jsxref("Promise.allSettled", "Promise.allSettled()")}}
+
Изчаква докато всички promises са приключени/уредени (всеки може да бъде разрешен или отказан).
+
Връща promise което се решава след всички дадени promises били те разрешени или отказани, с масив от обекти , които описват резултата от всеки promise.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Изчаква докато някой от promises е разрешен или отказан.
+
Ако върнатият promise е разрешен,е разрешен със стойноста от първият promise.Ако е отказан, е отакзан с причината от първият promise който е бил отказан.
+
{{jsxref("Promise.reject", "Promise.reject()")}}
+
Връща нов Promise обект, който е отказан с предоставена причина.
+
{{jsxref("Promise.resolve", "Promise.resolve()")}}
+
Връща нов Promise който е разрешен с дадената му стойност. Ако стойността е  thenable (i.e. има then метод), върнатият promise ще "следва" този thenable, приемайки евентуалното му състояние; в противен случай върнатия promise ще бъде запълнен със стойността. Обикновенно ако не знаете дадена стойност дали е promise или не, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} замества и работи с върнатата стойност като promise.
+
+ +

Promise прототип

+ +

Свойства

+ +

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

+ +

Методи

+ +

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

+ +

Създаване на Promise

+ +

Promise се създава, използвайки ключовата дума new и нейният конструктор. Този конструктор приема като аргумент функция, наричаща се "executor function". Тази функция трябва да приеме две функции като параметри. Първата от тези функции (resolve) се извиква когато асинхронната задача завърши успешно и върне резултата от задачата като стойност. Вторият (reject) се извиква когато задачата се провали и връща причината за този провал, който обикновенно е обект съдържайки в себе си грешката.

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

За да предоставите функция с promise функционалност, просто върнете promise:

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

Примери

+ +

Основни примери

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

Разширени примери

+ + + +

Този малък пример показва механизма на Promise. testPromise() метод се извиква всеки път когато  {{HTMLElement("button")}} е натиснат. Създава promise който ще бъде изпълнен, използвайки {{domxref("window.setTimeout()")}}, към promise броенето(номер започващ от 1) на всеки 1-3 секунди на случаен принцип. The Promise() се използва за създаването на promise.

+ +

Изпълнението на promise е просто записано, чрез сет за обратно извикване (callback set) , използвайки {{jsxref("Promise.prototype.then()","p1.then()")}}. Няколко logs (данни) показват как синхронната част на метода е отделена от асинхронното завършване на обещанието.

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

Този пример ще се стартира като кликнете на бутона. Имате нужда от браузер който поддържа Promise. Натискайки на бутона няколко пъти в кратки периоди от време , ще видите дори разллични promises , които се изпълняват един след друг.

+ +

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

+ +

Зареждане на снимка с XHR

+ +

Друг опростен пример използва Promise и {{domxref("XMLHttpRequest")}} за зареждане на снимки е наличен в GitHub профила на MDN и се казва js-examples. Тук също може да го видите и в действие see it in action. Всяка стъпка е коментирана и ви позволява да следвате Promise и XHR архитектурата внимателно.

+ +

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

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

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

+ + + +

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

+ +

See also

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