Arrays. Push arrays javascript examples

Arrays can be manipulated using various methods provided by the Array constructor.

Pop / push and shift / unshift methods

Consider the pop () and push () methods. These methods let you work with arrays like stacks. A stack is a data structure in which access to elements is organized according to the LIFO principle (English last in - first out, "last in - first out"). The principle of the stack can be compared to a stack of plates: to take the second from the top, you need to remove the top one. How it works is shown in the figure:

And so back to the consideration of the push () and pop () methods. The push () method adds one or more new elements to the end of the array and returns its new length. The pop () method - removes the last element of the array, decreases the length of the array and returns the value it removed. Note that both of these methods modify the array in place, rather than creating a modified copy of it.

Var foo \u003d; // foo: foo.push (1,2); // foo: Returns 2 foo.pop (); // foo: Returns 2 foo.push (3); // foo: Returns 2 foo.pop (); // foo: Returns 3 foo.push (); // foo:] Returns 2 foo.pop () // foo: Returns foo.pop (); // foo: Returns 1 var fruits \u003d ["pears", "bananas", "apples"]; var picked \u003d fruits.pop (); document.write ("You picked mine" + picked); Try "

The shift () and unshift () methods behave in much the same way as pop () and push (), except that they insert and remove elements at the beginning of the array. The unshift () method shifts existing elements towards larger indices to make room for new elements, adds one or more elements to the beginning of the array, and returns the new length of the array. The shift () method removes the first element of the array and returns its value, shifting all subsequent elements to occupy free space at the beginning of the array.

Var f \u003d; // f: f.unshift (1); // f: Returns: 1 f.unshift (22); // f: Returns: 2 f.shift (); // f: Returns: 22 f.unshift (3,); // f:, 1] Returns: 3 f.shift (); // f: [, 1] Returns: 3 f.shift (); // f: Returns: f.shift (); // f: Returns: 1

Join method

The Array.join () method is used to combine the elements of an array into one string. You can pass an optional string argument to the method, which will be used to separate the elements in the string. If no delimiter is specified, then the default delimiter character is the comma when the method is called.

Var a \u003d ["Wind", "Rain", "Fire"]; var myVar1 \u003d a.join (); // "Wind, Rain, Fire" var myVar2 \u003d a.join (","); // "Wind, Rain, Fire" var myVar3 \u003d a.join ("+"); // "Wind + Rain + Fire" document.write (myVar1 + "
"+ myVar2 +"
"+ myVar3); Try"

The Array.join () method is the opposite of the String.split () method, which creates an array by splitting a string into chunks.

Reverse method

The Array.reverse () method reverses the order of the elements in the array and returns the array with the rearranged elements. This method does not create a new array with reordered elements, but reorders them in an already existing array.

Var myArr \u003d ["one", "two", "three"]; document.write (myArr.reverse ()); Try "

The concat method

The Array.concat () method creates and returns a new array containing the elements of the original array on which the concat () method was called, sequentially padded with the values \u200b\u200bof all arguments passed to the concat () method. If any of these arguments are themselves an array, then all of its elements will be added. Array names are used as arguments and are specified in the order in which you want to concatenate their elements.

Var a \u003d; a.concat (4, 5) // Returns a.concat (); // same thing - returns a.concat (,) // Returns

Sort method

The Array.sort () method sorts the elements of the array in place and returns the sorted array. If the sort () method is called with no argument, then it sorts the elements of the array alphabetically (temporarily converts them to strings for comparison). The sort () method can take a comparison function as an argument, which determines the sort order of the items.

Var a \u003d ["Kiwi", "Oranges", "Pears"]; a.sort (); var s \u003d a.join (","); // Oranges, Pears, Kiwi document.write (s); // example with numbers var myArr \u003d; myArr.sort (); document.write (myArr); // 1,10,2 Try "

You probably expected to see a slightly different result from sorting numbers. This sort of sort occurs because the sort () method sorts the elements by converting them to strings. Therefore, the order they get is string - after all, "10"

To sort in any other non-alphabetical order, you can pass a comparison function as an argument to sort (). Note, however, that you have to write the comparison function yourself. This function must have two parameters, as it sets which of its two arguments should appear first in the sorted list. To make it easier to understand and write such a function, there are several rules by which the order of elements will be determined:

  • If the first argument must precede the second, the comparison function returns a negative number (if a
  • If the first argument must follow the second, then the comparison function returns a positive number (if a\u003e b)
  • If the two values \u200b\u200bare equivalent (i.e., their order is not important), the comparison function returns 0 (if a \u003d\u003d b)

For comparison, the function uses array elements as its arguments:

Function foo (a, b) (// define a test function if (a b) return 1; return 0; // if a \u003d\u003d b) var a \u003d; a.sort (foo); // only the function name is passed as an argument document.write (a.join (",")); // write the same thing shorter var a \u003d; a.sort (function (a, b) (// use the anonymous function return a - b; // function returns 0)); document.write (a); // 1,2,5,10 Try it "

The first entry in the example is written in such a way in order to make it easier to understand how it works. Notice how convenient it is to use an anonymous function in the second snippet. It is called only once, so there is no need to give it a name.

Note: If there are undefined elements in the array, they wrap to the end of the array.

Slice method

The Array.slice () method is used to copy the specified area from the array and returns a new array containing the copied elements. This does not change the original array.

Method syntax:

ArrayName.slice (begin, end);

Array_name should be replaced with the name of the array from which you want to extract a specific set of elements for a new array. The method takes two arguments that define the beginning and end of the returned portion of the array. The method copies a portion of the array from begin to end, not including end. If only one argument is specified, the returned array will contain all elements from the specified position to the end of the array. You can use negative indices - they are counted from the end of the array.

Var arr \u003d; arr.slice (0.3); // Returns arr.slice (3); // Returns arr.slice (1, -1); // Returns arr.slice (-3, -2); // Returns

Splice method

The Array.splice () method is a generic method for working with arrays. It modifies the array in place, rather than returning a new modified array like the slice () and concat () methods do. The splice method can remove elements from an array, insert new elements, replace elements - one at a time and simultaneously. It returns an array of the removed elements, if none of the elements were removed, it will return an empty array.

Method syntax:

ArrayName.splice (index, qty, elem1, ..., elemN);

The first argument specifies the index in the array at which to start inserting or removing elements. The second argument specifies the number of elements to be removed from the array starting from the index specified in the first argument, if the second argument is 0, then the elements will not be removed. If the second argument is omitted, all array elements from the specified index to the end of the array are removed. When using a negative position number, the elements will be counted from the end of the array.

Var fruits \u003d ["oranges", "apples", "pears", "grapes"]; var deleted \u003d fruits.splice (2,2); // returns ["pears", "grapes"] document.write (deleted); var arr \u003d; arr.splice (4); // Returns; the array is now: arr.splice (1,2); // Returns; the array became: arr.splice (1,1); // Returns; the array has become: Try "

The first two arguments to the splice () method specify the array elements to be removed. These two arguments can be followed by any number of additional arguments that specify the elements to be inserted into the array, starting at the position given by the first argument.

Var fruits \u003d ["oranges", "apples"]; fruits.splice (2,0, "watermelons"); // returns document.write (fruits); // now ["oranges", "apples", "watermelons"] var arr \u003d; arr.splice (2,0, "a", "b"); // Returns; became arr.splice (2,2,); // Returns ["a", "b"]; became, 3,4,5] Try "

Note that unlike concat (), the splice () method does not split the arrays passed as arguments into separate elements. That is, if an array is passed to a method for insertion, it inserts the array itself, not the elements of that array.

ToString method

The toString () method converts the elements of an array to a string using a comma as the separator character.

Var arr \u003d ["Milk", "Bread", "Cookies"]; var food \u003d arr.toString (); document.write (food); // Milk, Bread, Cookies Try it "

Note that the method returns the same string as join () when called with no arguments.

indexOf and lastIndexOf

The indexOf method returns the index of an element whose value is equal to the value passed to the method as an argument.

The syntax for the indexOf () and lastIndexOf () methods is:

Array_name.indexOf (lookup_item, index) array_name.lastIndexOf (lookup_item, index)

The first argument of the method specifies the value of the element whose index to find, the second argument (optional) specifies the index from which to start the search. If there are several identical occurrences, the smallest (first) index is selected. If an element with the desired value is not found, the method will return -1. Inside the method, strict comparison (\u003d\u003d\u003d) is used for searching.

Var a \u003d; a.indexOf (3); // will return 2 a.indexOf (3,4); // will return 6 a.indexOf (35); // returns -1: there is no element with this value a.indexOf (2); // 1

The lastIndexOf () method also returns the index of an element whose value is equal to the value passed to the method as an argument. The only difference is that the lastIndexOf () method selects the highest (last) index.

Var a \u003d; a.lastIndexOf (3); // will return 7 a.lastIndexOf (35); // returns -1: there is no element with this value a.lastIndexOf (2); // 6

Iterator methods

The methods described below are iterators. All modern browsers for working with arrays have methods that are designed to iterate over elements and perform various actions on them. These are forEach (), map (), filter (), every (), some, reduce () and reduceRight () methods.

They iterate over the array elements from 0 to length - 1 and, if the element exists, pass it to the callback handler function.

forEach

Method syntax:

ArrayName.forEach (callback, thisArg)

The first argument is a callback function that the forEach () method will call for each element of the array. You need to write the implementation of the called handler function yourself. The called function must have three parameters: the first parameter takes as an argument the value of the array element, the second - the element's index, and the third - the array itself. However, if you want to use only the values \u200b\u200bof the array elements, you can write a function with only one parameter. The second argument, thisArg (optional), will be passed as the this value.

Var arr \u003d; function foo (value) (var sum \u003d value * this; return document.write (sum + "
");) arr.forEach (foo, 5); // the second argument will be passed as the value this // example with three parameters var a \u003d; a.forEach (function (el, idx, a) (document.write ( "a [" + idx + "] \u003d" + el + "in [" + a + "]
");)); Try"

filter

Method syntax:

Arrayname.filter (callback, thisObject)

The filter () method creates and returns a new array that will contain only those array elements for which the callback function will return true.

Function isBig (element, index, array) (// returns numbers that are greater than or equal to 10 return (element\u003e \u003d 10); // if the element value is greater than or equal to 10, the expression will return true) var filtered \u003d .filter (isBig) ; // filtered

map

The map () method creates and returns a new array, which will consist of the results of calling the callback (item, idx, ar) function for each element in the array.

Var a \u003d; var b \u003d a.map (function (item, idx, arr) (return item * item;)); // b \u003d

every and some

Every () method returns true if the specified function used to test them returns true for all elements of the array.

The some () method returns true if, during validation in the specified function, one or more elements return true.

Var a \u003d; a.every (function (x) (return x 10;)) // true: one number\u003e 10

reduce and reduceRight

Method syntax:

ArrayName.reduce (callback, initialValue) ArrayName.reduceRight (callback, initialValue)

The reduce () method applies the specified function (callback) against two values \u200b\u200bin the array at once, iterating over the elements from left to right, while maintaining the intermediate result.

Callback function arguments: (previousValue, currentItem, index, array)

  • previousValue - the return result of the callback function (aka intermediate result)
  • currentItem - the current item in the array (items are iterated from left to right in turn)
  • index - the index of the current element
  • array - the array being processed

initialValue The object used as the first argument to the first call to the callback function. In simpler terms, the value of previousValue is equal to initialValue when first called. If initialValue is absent, then it is equal to the first element of the array, and the iteration starts from the second:

Var a \u003d; function foo (prevNum, curNum) (sum \u003d prevNum + curNum; alert (sum); return sum;) var result \u003d a.reduce (foo, 0); document.write (result); Try "

Let's see how this example works. The first arguments to foo are:

  • prevNum \u003d 0 (since initialValue is 0)
  • curNum \u003d 1 (current element is the 1st element of the array)

The number 0 is added to 1. This result (sum: 1) will be passed as prevNum the next time the function is run. And so on until it comes to the last element. The returned result - the sum from the last run, will be 15 (1 + 2 + 3 + 4 + 5).

The reduceRight method works similarly to the reduce method, but goes through the array from right to left:

Var a \u003d ["h", "o", "m", "e"]; function bar (prevStr, curItem) (return prevStr + curItem;) document.write (a.reduceRight (bar)); // emoh

Arrays

Array is an ordered collection of values. The values \u200b\u200bin an array are called elements, and each element is characterized by a numeric position in the array, called an index. Arrays in JavaScript are untyped: the elements of an array can be of any type, and different elements of the same array can be of different types. Array elements can even be objects or other arrays, which allows you to create complex data structures such as arrays of objects and arrays of arrays.

Array indices in JavaScript are zero-based and use 32-bit integers — the first element of an array has index 0. JavaScript arrays are dynamic: they can grow and shrink as needed; there is no need to declare fixed sizes of arrays when they are created or to re-allocate memory when they are resized.

Arrays in JavaScript are a specialized form of objects, and array indices mean little more than just property names, which coincidentally are integers.

Creating arrays

The easiest way to create an array is with a literal, which is a simple comma-separated list of array elements in square brackets. The values \u200b\u200bin an array literal do not have to be constants - they can be any expressions, including object literals:

Var empty \u003d; // Empty array var numbers \u003d; // Array with five numeric elements var misc \u003d [1.1, true, "a",]; // 3 elements of different types + trailing comma var base \u003d 1024; var table \u003d; // Array with variables var arrObj \u003d [,]; // 2 arrays inside containing objects

The array literal syntax allows you to insert an optional trailing comma, i.e. literal [,] matches an array with two elements, not three.

Another way to create an array is to call the constructor Array ()... The constructor can be called in three different ways:

    Call the constructor with no arguments:

    Var arr \u003d new Array ();

    In this case, an empty array equivalent to the literal will be created.

    Call the constructor with a single numeric argument specifying the length of the array:

    Var arr \u003d new Array (10);

    In this case, an empty array of the specified length will be created. This form of calling the Array () constructor can be used to pre-allocate memory for an array if the number of its elements is known in advance. Note that this does not store any values \u200b\u200bin the array.

    Explicitly specify the values \u200b\u200bof the first two or more array elements or one non-numeric element in a constructor call:

    Var arr \u003d new Array (5, 4, 3, 2, 1, "test");

    In this case, the arguments to the constructor become the values \u200b\u200bof the elements of the new array. Using array literals is almost always easier than using the Array () constructor in this way.

Reading and writing array elements

Array elements are accessed using the operator. There must be an array reference to the left of the parentheses. An arbitrary expression that returns a non-negative integer value must be inside the parentheses. This syntax is suitable for both reading and writing the value of an array element. Therefore, all of the following JavaScript statements are valid:

// Create an array with one element var arr \u003d ["world"]; // Read item 0 var value \u003d arr; // Write the value to element 1 arr \u003d 3.14; // Write a value to element 2 i \u003d 2; arr [i] \u003d 3; // Write a value to element 3 arr \u003d "hello"; // Read items 0 and 2, write the value to item 3 arr] \u003d arr;

Let me remind you that arrays are a specialized kind of object. The square brackets used to access array elements act exactly the same as the square brackets used to access object properties. The JavaScript interpreter converts the parenthesized numeric indexes to strings - index 1 becomes the string "1" - and then uses the strings as property names.

There is nothing special about converting numeric indices to strings: the same can be done with regular objects:

Var obj \u003d (); // Create a simple object obj \u003d "one"; // Index it with integers

The peculiarity of arrays is that when using property names that are non-negative integers, the arrays automatically determine the value of the property length... For example, the arr array was created above with a single element. Then, values \u200b\u200bwere assigned to its elements with indices 1, 2, and 3. As a result of these operations, the value of the length property of the array changed and became equal to 4.

You should clearly distinguish between indexes in an array and object property names. All indexes are property names, but only properties with integer names are indexes. All arrays are objects, and you can add properties to them with any name. However, if you touch properties that are array indices, arrays respond by updating the value of the length property as needed.

Note that negative and non-integers are allowed as array indices. In this case, numbers are converted to strings that are used as property names.

Adding and Removing Array Elements

We have already seen that the easiest way to add elements to an array is to assign values \u200b\u200bto new indices. You can also use the method to add one or more elements to the end of an array push ():

Var arr \u003d; // Create an empty array arr.push ("zero"); // Add a value to the end arr.push ("one", 2); // Add two more values

You can also add an element to the end of an array by assigning a value to the arr element. To insert an element at the beginning of an array, you can use the method unshift ()and the existing elements in the array are shifted to higher indices.

You can delete elements of an array using the delete operator, like ordinary properties of objects:

Var arr \u003d; delete arr; 2 in arr; // false, index 2 in the array is undefined arr.length; // 3: the delete operator does not change the length property of the array

Removing an element is similar (but slightly different) to assigning an undefined value to that element. Note that applying the delete operator to an element in an array does not change the value of the length property, nor does it move down the elements with higher indices to fill the void left after the element is deleted.

It is also possible to remove elements at the end of an array by simply assigning a new value to the length property. Arrays have a method pop () (opposite to push ()), which decreases the length of the array by 1 and returns the value of the removed element. There is also a method shift () (opposite to unshift ()), which removes the element at the beginning of the array. Unlike the delete operator, the shift () method shifts all elements down one position below their current indices.

Finally there is a multipurpose method splice ()that allows you to insert, delete, and replace array elements. It changes the value of the length property and shifts the elements of the array with lower or higher indices as needed. We will discuss all these methods a little later.

Multidimensional arrays

JavaScript does not support "real" multidimensional arrays, but it does a good job of simulating them using arrays from arrays. To access a data item in an array of arrays, it is sufficient to use the operator twice.

For example, suppose the variable matrix is \u200b\u200ban array of arrays of numbers. Each element of matrix [x] is an array of numbers. You can use the expression matrix [x] [y] to access a specific number in an array. Below is a specific example where a two-dimensional array is used as a multiplication table:

// Create a multidimensional array var table \u003d new Array (10); // There are 10 rows in the table for (var i \u003d 0; i

Array class methods

The ECMAScript 3 standard defines many convenient functions for working with arrays as part of Array.prototype, which are available as methods of any array. These methods will be presented in the following subsections.

Join () method

The Array.join () method converts all the elements in the array to strings, concatenates them, and returns the resulting string. An optional argument can be passed to the method with a string that will be used to separate items in the result string. If no delimiter string is specified, a comma is used. For example, the following snippet results in the string "1,2,3":

Var arr \u003d; arr.join (); // "1,2,3" arr.join ("-"); // "1-2-3"

The reverse () method

The Array.reverse () method reverses the order of the elements in an array and returns a reordered array. The permutation is done directly on the original array, i.e. this method does not create a new array with reordered elements, but reorders them in an already existing array. For example, the following snippet, which uses the reverse () and join () methods, results in the string "3,2,1":

Var arr \u003d; arr.reverse (). join (); // "3,2,1"

Sort () method

The Array.sort () method sorts the elements in the original array and returns the sorted array. If sort () is called with no arguments, sorting is done alphabetically (for comparison, items are temporarily converted to strings if necessary). Undefined elements are wrapped to the end of the array.

You can pass a comparison function as an argument to sort () to sort in any other non-alphabetical order. This function sets which of its two arguments should come first in the sorted list. If the first argument must precede the second, the comparison function must return a negative number. If the first argument is to follow the second in the sorted array, then the function must return a number greater than zero. And if the two values \u200b\u200bare equivalent (i.e., the order is not important), the comparison function should return 0:

Var arr \u003d; arr.sort (); // Alphabetical order: 1111, 222, 33, 4 arr.sort (function (a, b) (// Numeric order: 4, 33, 222, 1111 return ab; // Returns the value 0 // depending on the sort order a and b)); // Sort backwards, from highest to lowest arr.sort (function (a, b) (return b-a));

Notice how convenient it is to use an unnamed function in this snippet. The comparison function is only used here, so there is no need to give it a name.

The concat () method

The Array.concat () method creates and returns a new array containing the elements of the original array on which the concat () method was called and the values \u200b\u200bof all arguments passed to the concat () method. If any of these arguments are themselves an array, its elements are added to the returned array. It should be noted, however, that there is no recursive conversion of an array from arrays to a one-dimensional array. The concat () method does not modify the original array. Below are some examples:

Var arr \u003d; arr.concat (4, 5); // Returns arr.concat (); // Returns arr.concat (,) // Returns arr.concat (4,]) // Returns]

Slice () method

The Array.slice () method returns a slice, or subarray, of the specified array. The two arguments to the method define the start and end of the returned chunk. The returned array contains the element numbered in the first argument plus all subsequent elements up to (but not including) the element numbered in the second argument.

If only one argument is specified, the returned array contains all elements from the starting position to the end of the array. If any of the arguments are negative, it specifies the element number relative to the end of the array. Thus, argument -1 corresponds to the last element of the array, and argument -3 corresponds to the third element of the array from the end. Here are some examples:

Var arr \u003d; arr.slice (0.3); // Returns arr.slice (3); // Returns arr.slice (1, -1); // Returns arr.slice (-3, -2); // Will return

Splice () method

The Array.splice () method is a generic method that inserts or removes elements from an array. Unlike the slice () and concat () methods, the splice () method modifies the original array on which it was called. Note that the splice () and slice () methods have very similar names but perform completely different operations.

The splice () method can remove elements from an array, insert new elements, or do both at the same time. The elements of the array are shifted as necessary so that after insertion or deletion, a contiguous sequence is formed.

The first argument to the splice () method specifies the position in the array from which to insert and / or delete. The second argument specifies the number of elements to be removed (cut) from the array. If the second argument is omitted, all array elements from the specified array to the end of the array are removed. The splice () method returns an array of the removed elements, or (if none of the elements have been removed) an empty array.

The first two arguments to the splice () method specify the array elements to be removed. These arguments can be followed by any number of additional arguments that specify the elements to be inserted into the array, starting at the position specified in the first argument.

Var arr \u003d; arr.splice (4); // Returns arr \u003d arr.splice (1,2); // Returns arr \u003d arr.splice (1,1); // Will return; arr \u003d arr \u003d; arr.splice (2,0, "a", "b"); // Will return; arr \u003d

The push () and pop () methods

The push () and pop () methods let you work with arrays like stacks. The push () method adds one or more new elements to the end of the array and returns its new length. The pop () method performs the opposite operation - it removes the last element of the array, decreases the length of the array, and returns the value it removed. Note that both of these methods modify the original array rather than creating a modified copy of it.

The unshift () and shift () Methods

The unshift () and shift () methods behave in much the same way as push () and pop (), except that they insert and remove elements at the beginning of the array rather than at the end. The unshift () method shifts existing elements towards larger indices to make room, adds the element or elements to the beginning of the array, and returns the new length of the array. The shift () method removes and returns the first element of the array, shifting all subsequent elements down one position to occupy the space vacated at the beginning of the array.

The push () method adds one or more elements to the end of an array and returns the new length of the array.

The source for this interactive example is stored in a GitHub repository. If you "d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

arr .push (element1 [, ... [, elementN]])

Parameters

element N The element (s) to add to the end of the array.

Return value

Examples

Adding elements to an array

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

Let sports \u003d ["soccer", "baseball"] let total \u003d sports.push ("football", "swimming") console.log (sports) // ["soccer", "baseball", "football", "swimming "] console.log (total) // 4

Merging two arrays

This example uses apply () to push all elements from a second array.

Do not use this method if the second array (moreVegs in the example) is very large, because the maximum number of parameters that one function can take is limited in practice. See apply () for more details.

Let vegetables \u003d ["parsnip", "potato"] let moreVegs \u003d ["celery", "beetroot"] // Merge the second array into the first one // Equivalent to vegetables.push ("celery", "beetroot") Array.prototype.push.apply (vegetables, moreVegs) console.log (vegetables) // ["parsnip", "potato", "celery", "beetroot"]

Using an object in an array-like fashion

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don "t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array-and it just works, thanks to the way JavaScript allows us to establish the execution context however we please.

Let obj \u003d (length: 0, addElem: function addElem (elem) (// obj.length is automatically incremented // every time an element is added. .Push.call (this, elem))) // Let "s add some empty objects just to illustrate.obj.addElem (()) obj.addElem (()) console.log (obj.length) // → 2

Note that although obj is not an array, the method push successfully incremented obj "s length property just like if we were dealing with an actual array.

Specifications

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Array.prototype.push" in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of "Array.prototype.push" in that specification.
Draft

Browser compatibility

The compatibility table in this page is generated from structured data. If you "d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
pushChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support YesSafari Full support 1WebView Android Full support YesChrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support Yesnodejs Full support Yes

The stack allows you to refer to the data the history of changing values \u200b\u200bof variables. Describing data and algorithms is at the heart of programming. The stack is the basis for transferring control between functions, organizing recursion and parameter references. JavaScript syntax and semantics, through the push () and pop () array methods, make it possible to manipulate meaning and take into account the time factor. The peculiarity of the browser language and its logic allow us to look differently at the possibilities of the time factor.

Data array and logic of its formation

Just describe the variable. It's not hard to create an array of variables. An algorithm using data is a static and simple solution to a problem. Classic data manipulation:

  • describe (create) a variable;
  • assign a value;
  • change the value;
  • remove variable.

The push () and pop () functions allow you to change the nature of variables and their use. The idea of \u200b\u200ba stack has not changed since its "birth", but the peculiarity of JS as a browser language and a modern programming concept allows you to take into account the time factor and give dynamics to the data.

The value ") function is to add something to the end of the array. The function is to retrieve the last element of the array. The pointer in the push / pop context, when added, moves to the added element, when retrieved, to the penultimate element, and the last element is the result of the operation.

A stack of plates - the traditional description of a stack in JavaScript - takes on a new meaning. Let the variable always be an array. An array itself is a collection of variables, but considering a variable as an array, you can look differently at the dynamics of changing its values.

Movement by values

The essence of the stack - came in last, left first. You cannot extract a value out of this order. Strictly observing this rule, considering the values \u200b\u200bof the entire array as one variable, you can get the dynamics of changes in the values \u200b\u200bof this variable over time.

In this example, adding JS array.push (...) values \u200b\u200bis one sequence of actions, retrieving JS array pop () values \u200b\u200bis another sequence. Both courses of action are interrelated. This means that the active element changes its value not only in time, but also in the logic of its change.

Recursion and value dynamics

If a function can call itself and safely fulfill its purpose, that is full functionality. A simple example is a table. There may be other tables in the table. And each table is rows, columns and cells. Each cell can contain a table. Several cells by row or by column can be combined into one cell, which can contain a table. In a table in a cell, there can be a cell with two or more tables.

It is almost impossible to implement what was said in the classical programming style, but in the recursive style it is elementary. If the functionality of the algorithm for working with the table allows itself to be implemented inside any cell, then this is JS array push. This trick has a special meaning in JavaScript. Tables are custom use. The page tree (DOM) is the work on the page.

Handlers hang on DOM elements (page tags). One option, when such a handler is triggered once, is a completely different option, when it can call itself many times. In the context of all handlers of all page elements, the dynamics of the page in time is obtained.

Push / pop and recursion are a slightly different view of the logic of the page: everything changes as required in the current situation, and is not programmed in advance in the form of sequential processing of the visitor's actions.

In JavaScript. Here we will continue our acquaintance with Arrays. Let's talk about the length property - how do you know: how many elements does an Array contain?

Let's learn add items to the beginning and end of the Array are the unshift and push methods, respectively.

And also using the shift and pop methods we can remove items also from the beginning and end of the Array!

Essentially, an Array is an object made up of a certain number of different elements.

The length property allows you to find out the number of elements in the Array.

For example, let's take the Array of seven days of the week familiar to us from the previous topic.

Let's find out and display the number of elements in the array. To do this, as you can see in the example below, create a variable whose value will be the array of interest to us, for which, in turn, the length property is specified.

array.length - this code gives us the number of elements of the Array (Where array - Array name) .

Thus, we put a number in the count variable equal to the number of elements in the Array.

This is how the length property works.

Push method - adds an item to the end of the Array.

In order to start working with methods for adding elements, you need to create an Array.

Below I have created an Array "Friends" - friends.

Now we need to add an element, that is, another Name at the end of the Array.

There is a push method for this - it adds an item to the end of the Array. It looks like this:

Nastya, Grigory, Vyacheslav, Alexey, Yakov

Jacob

To test the work of the push method in the example above, we deduced the number of elements of the friends Array using the length property - there are 5 of them. Then we displayed the entire friends Array, as well as last element of Array .

Now you can see for yourself that the element is added to the end of the Array!

Unshift method - add item to the beginning of the Array.

Here we refer to the friends Array again.

Now we need to add an element to the beginning of the Array. There is an unshift method for this.

The number of elements in the Array is 5

Boris, Nastya, Grigory, Vyacheslav, Alexey

Boris

To test the operation of the unshift method, we deduced the number of elements of the friends Array using the length property, then we displayed the entire friends Array, as well as first element of Array (recall that the numbering of Array elements starts from 0) .

Now, as you can see, the element is added to the beginning of the Array!

Pop method - removes last element from Array.

And again we work with the Array "Friends"

Using the pop method - remove the last element from the Array:

Nastya, Grigory, Vyacheslav

Vyacheslav

For clarity of the pop method, we again deduced the number of Array elements using the length property, then we deduced the entire Friends Array - without the last element removed.

And also brought last element the resulting Array ... To display the last element, using the length property, we took the total number of remaining elements in Array (3) and subtracted 1. Thus, we displayed the last element of the array at number 2. But this is the third element, since the numbering in the Array starts with 0 !!!

Shift method - removes first element from Array.

Before us, as before, the Array "Friends"

With the shift method - remove the first element from the Array:

The number of elements in the Array is 3

Gregory, Vyacheslav, Alexey

Gregory

And, finally, to test the operation of the shift method, we deduced the number of elements of the newly obtained Array using the length property, then we deduced the entire Array friends - without the first element removed.

And also brought first element of Array... Numbering in the Array starts from 0 !!!

I will remind you and for myself one interesting moment of this article!

In order to find out the number / index of the last element of the Array, you need from the number of its elements (i.e. from) Subtract one !!!

We already worked with this in the topic paragraph.

A good example of this point would be a continuation of the example from the topic paragraph, where we looked at the Array of seven days of the week.

The number of elements in Array days is 7

The number of the last element of the Array is 6

So, with this example, we at the same time once again noted the fact that array numbering starts from 0... And, as you can see from this example, the 7th element of the array is 6.

At the end of this topic, we will also do our homework. Again, try to solve it yourself.

The homework for removing from ... and adding elements to an Array in Javascript has the following content:

1. Create an array with fruits: orange, banana, pear.
2. Print on the screen how many fruits you currently have in the array.
3. Using the methods learned in the previous lesson, add two fruits to the end of the array - an apple and a pineapple, and to the beginning of the array - a grapefruit.
4. Display how many fruits you currently have in the array.
5. Using the methods you learned in the previous lesson, remove the last and first element from the array.
6. Display how many fruits you currently have in the array.

Orange, Banana, Pear

Now there are 3 fruits in my basket

Grapefruit, Orange, Banana, Pear, Apple, Pineapple

Now there are 6 fruits in my basket

Orange, Banana, Pear, Apple

Now there are 4 fruits in my basket