All the ways to iterate over an array in JavaScript. JQuery - Iterate Array, Object and Elements Convert to Real Array

Not so long ago, it took me to JavaScript create associative array... Amazingly, I never needed him before. JavaScript... I started searching the Internet for how to make it. And I was very surprised that a huge number of people write that this is impossible, in JavaScript it is not. Fortunately, my many years of experience told me that they are nonsense. So in the end I found out how to create associative array in JavaScript, which I will tell you about in this article.

Below is the code in which an associative array is created, then one more element is added and, finally, the array is iterated through the loop:

In this article, we covered creating associative arrays, their change, as well as full enumeration through the cycle for... I personally have used associative arrays in JavaScript only once, but you must be aware of such a possibility.

  • I. Iterating over real arrays
    1. ForEach and related methods
    2. For loop
    3. Correct use of for ... in loop
    4. For ... of loop (implicit use of an iterator)
    5. Explicit use of an iterator
    1. Using methods to iterate over real arrays
    2. Converting to a real array
    3. A note on runtime objects

I. Iterating over real arrays

At the moment, there are three ways to iterate over the elements of a real array:
  1. array.prototype.forEach method;
  2. classic for loop;
  3. A well-formed for ... in loop.
In addition, soon, with the emergence of the new ECMAScript 6 (ES 6) standard, two more ways are expected:
  1. for ... of loop (implicit use of an iterator);
  2. explicit use of an iterator.

1. The forEach method and related methods

If your project is designed to support the capabilities of the ECMAScript 5 (ES5) standard, you can use one of its innovations - the forEach method.

Usage example:
var a \u003d ["a", "b", "c"]; a.forEach (function (entry) (console.log (entry);));
In general, using forEach requires connecting the es5-shim emulation library for browsers that do not have native support for this method. These include IE 8 and earlier, which are still in use today.

The advantage of forEach is that there is no need to declare local variables to store the index and value of the current array element, since they are automatically passed to the callback function as arguments.

If you're worried about the potential cost of calling a callback for each item, don't worry and read this.

ForEach is designed to iterate over all the elements of an array, but besides it, ES5 offers several more useful methods for iterating over all or some of the elements, plus performing some actions with them:

  • every - returns true if for each element of the array the callback returns a value that is cast to true.
  • some - returns true if for at least one element of the array the callback returns a value that is cast to true.
  • filter - creates a new array containing those elements of the original array for which the callback returns true.
  • map - creates a new array containing the values \u200b\u200breturned by the callback.
  • reduce - reduces an array to a single value, applying the callback in turn to each element of the array, starting from the first (can be useful for calculating the sum of array elements and other final functions).
  • reduceRight - works similar to reduce, but iterates over the elements in reverse order.

2. The for loop

Good old for rules:

Var a \u003d ["a", "b", "c"]; var index; for (index \u003d 0; index< a.length; ++index) { console.log(a); }
If the length of the array remains unchanged throughout the entire loop, and the loop itself belongs to a performance-critical piece of code (which is unlikely), then you can use the "more optimal" version of for with storing the length of the array:

Var a \u003d ["a", "b", "c"]; var index, len; for (index \u003d 0, len \u003d a.length; index< len; ++index) { console.log(a); }
In theory, this code should run slightly faster than the previous one.

If the order of iteration is not important, then you can go even further in terms of optimization and get rid of the variable for storing the length of the array by changing the iteration order to the opposite:

Var a \u003d ["a", "b", "c"]; var index; for (index \u003d a.length - 1; index\u003e \u003d 0; --index) (console.log (a);)
However, in modern JavaScript engines, these optimized games usually mean nothing.

3. Correct use of the for ... in loop

If you are advised to use a for ... in loop, remember that iterating over arrays is not what it is intended for. Contrary to the common misconception, the for ... in loop does not iterate over the array indices, but the enumerated properties of the object.

However, in some cases, such as iterating over sparse arrays, for ... in can be useful, as long as you take some precautions, as shown in the example below:

// a is a sparse array var a \u003d; a \u003d "a"; a \u003d "b"; a \u003d "c"; for (var key in a) (if (a.hasOwnProperty (key) && /^0$|^\\d*$/.test(key) && key<= 4294967294) { console.log(a); } }
In this example, at each iteration of the loop, two checks are performed:

  1. that the array has its own property named key (not inherited from its prototype).
  2. that key is a string containing the decimal notation of an integer whose value is less than 4294967294. Where does the last number come from? From the definition of an array index in ES5, from which it follows that the largest index an element in an array can have is (2 ^ 32 - 2) \u003d 4294967294.
Of course, such checks will take up extra time when executing the loop. But in the case of a sparse array, this method is more efficient than a for loop, since in this case only those elements that are explicitly defined in the array are iterated over. So, in the example above, only 3 iterations will be performed (for indices 0, 10 and 10000) - versus 10001 in the for loop.

In order not to write such a cumbersome code of checks every time you need to iterate over an array, you can design it as a separate function:

Function arrayHasOwnIndex (array, key) (return array.hasOwnProperty (key) && /^0$|^\\d*$/.test(key) && key<= 4294967294; }
Then the body of the loop from the example will be significantly reduced:

For (key in a) (if (arrayHasOwnIndex (a, key)) (console.log (a);))
The above code of checks is universal, suitable for all cases. But instead, you can use a shorter version, although formally not quite correct, but nevertheless suitable for most cases:

For (key in a) (if (a.hasOwnProperty (key) && String (parseInt (key, 10)) \u003d\u003d\u003d key) (console.log (a);))

4. The for ... of loop (implicit use of an iterator)

ES6, while still in draft status, should introduce iterators into JavaScript.

Iterator is an object-implemented protocol that defines a standard way to obtain a sequence of values \u200b\u200b(finite or infinite).
An iterator is an object in which the next () method is defined - a function without arguments that returns an object with two properties:

  1. done (boolean) - true if the iterator has reached the end of the sequence being iterated. Otherwise, false.
  2. value - defines the value returned by the iterator. May be undefined (absent) if done property is true.
Many built-in objects, incl. real arrays have default iterators. The simplest way to use an iterator on real arrays is to use the new for ... of construct.

An example of using for ... of:

Var val; var a \u003d ["a", "b", "c"]; for (val of a) (console.log (val);)
In the above example, the for ... of loop implicitly calls the iterator of the Array object to get each value in the array.

5. Explicit use of an iterator

Iterators can also be used explicitly, however, in this case the code becomes much more complicated compared to the for ... of loop. It looks like this:

Var a \u003d ["a", "b", "c"]; var it \u003d a.entries (); var entry; while (! (entry \u003d it.next ()). done) (console.log (entry.value);)
In this example, the Array.prototype.entries method returns an iterator that is used to display the values \u200b\u200bof the array. At each iteration, entry.value contains an array like [key, value].

II. Looping through array-like objects

In addition to real arrays, JavaScript also contains array-like objects ... What they have in common with real arrays is that they have a length property and properties with names in the form of numbers corresponding to the elements of the array. Examples include the DOM of the NodeList collection and the arguments pseudo-array available inside any function / method.

1. Using methods of iterating over real arrays

At least most, if not all, methods of iterating over real arrays can be used to iterate over array-like objects.

The for and for ... in constructs can be applied to array-like objects in exactly the same way as they can to real arrays.

ForEach and other Array.prototype methods also apply to array-like objects. To do this, you need to use a call to Function.call or Function.apply.

For example, if you want to apply forEach to the childNodes property of a Node object, you can do it like this:

Array.prototype.forEach.call (node.childNodes, function (child) (// do something with the child object));
For ease of reuse of this technique, you can declare a reference to the Array.prototype.forEach method in a separate variable and use it as a shorthand:

// (This assumes all the code below is in the same scope) var forEach \u003d Array.prototype.forEach; // ... forEach.call (node.childNodes, function (child) (// do something with the child object));
If an array-like object has an iterator, then it can be used explicitly or implicitly to iterate over the object in the same way as for real arrays.

2. Convert to a real array

There is also another, very simple, way to iterate over an array-like object: convert it to a real array and use any of the above methods to iterate over real arrays. For conversion, you can use the generic Array.prototype.slice method, which can be applied to any array-like object. This is done very simply, as shown in the example below:

Var trueArray \u003d Array.prototype.slice.call (arrayLikeObject, 0);
For example, if you want to convert a NodeList collection to a real array, you need code like this:

Var divs \u003d Array.prototype.slice.call (document.querySelectorAll ("div"), 0);
Update: As noted in the comments by rock and torbasow, in ES6 you can use the more descriptive Array.from method instead of Array.prototype.slice.

3. A note on runtime objects

If you apply Array.prototype methods to runtime objects (such as DOM collections), then you should keep in mind that these methods are not guaranteed to work correctly in all runtime environments (including browsers). It depends on the behavior of a particular object in a particular runtime, more precisely, on how the HasProperty abstract operation is implemented in this object. The problem is that the ES5 standard itself allows for the possibility of object misbehaving with respect to this operation (see §8.6.2).

Therefore, it is important to test the Array.prototype methods in every runtime (browser) in which you plan to use your application.

The forEach () method executes a provided function once for each array element.

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 .forEach (callback (currentValue [, index [, array]]) [, thisArg])

Parameters

callback Function to execute on each element. It accepts between one and three arguments: currentValue The current element being processed in the array. index Optional The index currentValue in the array. array Optional The array forEach () was called upon. thisArg Optional Value to use as this when executing callback.

Return value

Description

forEach () calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized. (For sparse arrays,.)

callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

If a thisArg parameter is provided to forEach (), it will be used as callback "s this value. The thisArg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

The range of elements processed by forEach () is set before the first invocation of callback. Elements which are appended to the array after the call to forEach () begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach () visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift ()) during the iteration, later elements will be skipped. (See this example, below.)

forEach () executes the callback function once for each array element; unlike map () or reduce () it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

forEach () does not mutate the array on which it is called. (However, callback may do so)

There is no way to stop or break a forEach () loop other than by throwing an exception. If you need such behavior, the forEach () method is the wrong tool.

Early termination may be accomplished with:

Array methods: every (), some (), find (), and findIndex () test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Examples

No operation for uninitialized values \u200b\u200b(sparse arrays)

const arraySparse \u003d let numCallbackRuns \u003d 0 arraySparse.forEach (function (element) (console.log (element) numCallbackRuns ++)) console.log ("numCallbackRuns:", numCallbackRuns) // 1 // 3 // 7 // numCallbackRuns: 3 // comment: as you can see the missing value between 3 and 7 didn "t invoke callback function.

Converting a for loop to forEach

const items \u003d ["item1", "item2", "item3"] const copy \u003d // before for (let i \u003d 0; i< items.length; i++) { copy.push(items[i]) } // after items.forEach(function(item){ copy.push(item) })

Printing the contents of an array

Note: In order to display the content of an array in the console, you can use console.table (), which prints a formatted version of the array.

The following example illustrates an alternative approach, using forEach ().

The following code logs a line for each element in an array:

Function logArrayElements (element, index, array) (console.log ("a [" + index + "] \u003d" + element)) // Notice that index 2 is skipped, since there is no item at // that position in the array ... .forEach (logArrayElements) // logs: // a \u003d 2 // a \u003d 5 // a \u003d 9

Using thisArg

The following (contrived) example updates an object "s properties from each entry in the array:

Function Counter () (this.sum \u003d 0 this.count \u003d 0) Counter.prototype.add \u003d function (array) (array.forEach (function (entry) (this.sum + \u003d entry ++ this.count), this ) // ^ ---- Note) const obj \u003d new Counter () obj.add () obj.count // 3 obj.sum // 16

Since the thisArg parameter (this) is provided to forEach (), it is passed to callback each time it "s invoked. The callback uses it as its this value.

An object copy function

The following code creates a copy of a given object.

There are different ways to create a copy of an object. The following is just one way and is presented to explain how Array.prototype.forEach () works by using ECMAScript 5 Object. * Meta property functions.

Function copy (obj) (const copy \u003d Object.create (Object.getPrototypeOf (obj)) const propNames \u003d Object.getOwnPropertyNames (obj) propNames.forEach (function (name) (const desc \u003d Object.getOwnPropertyDescriptor (obj, name) Object .defineProperty (copy, name, desc))) return copy) const obj1 \u003d (a: 1, b: 2) const obj2 \u003d copy (obj1) // obj2 looks like obj1 now

If the array is modified during iteration, other elements might be skipped.

The following example logs "one", "two", "four".

When the entry containing the value "(! LANG: two" is reached, the first entry of the whole array is shifted off-resulting in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped.!}

forEach () does not make a copy of the array before iterating.

Let words \u003d ["one", "two", "three", "four"] words.forEach (function (word) (console.log (word) if (word \u003d\u003d\u003d "two") (words.shift ( )))) // one // two // four

Flatten an array

The following example is only here for learning purpose. If you want to flatten an array using built-in methods you can use Array.prototype.flat () (which is expected to be part of ES2019, and is already implemented in some browsers).

/ ** * Flattens passed array in one dimensional array * * @params (array) arr * @returns (array) * / function flatten (arr) (const result \u003d arr.forEach ((i) \u003d\u003e (if (Array. isArray (i)) (result.push (... flatten (i))) else (result.push (i)))) return result) // Usage const problem \u003d, 8, 9]] flatten (problem) / /

Note on using Promises or async functions

let ratings \u003d let sum \u003d 0 let sumFunction \u003d async function (a, b) (return a + b) ratings.forEach (async function (rating) (sum \u003d await sumFunction (sum, rating))) console.log (sum) // Expected output: 14 // Actual output: 0

Specifications

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

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
forEachChrome Full support 1Edge Full support 12Firefox Full support 1.5IE Full support 9Opera Full support YesSafari Full support 3WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes

An article in which we will look at examples using the jQuery each function and method.

The jQuery library has 2 different entities named each.

The first (jQuery.each) is a generic jQuery function that can be used to iterate over the elements of an array or object.

The second (each) is a method that is applied to a set of items to loop over them.

Each loop (jQuery.each). Examples of using

The syntax for the each function is:

// array or object - an array or an object whose elements or properties must be iterated over // callback - a function that will be executed for each element of an array or object's property $ .each (array or object, callback);

Let's look at the examples to work with the each function.

Example # 1. In it, we will iterate over all the elements of the array.

// an array of 3 lines var arr \u003d ["Car", "Truck", "Bus"]; // iterate over the array arr $ .each (arr, function (index, value) (// actions that will be performed for each element of the array // index is the current index of the array element (number) // value is the value of the current array element // print the index and value of the array to the console console.log ("Index:" + index + "; Value:" + value);)); / * Result (in console): Index: 0; Value: Car Index: 1; Value: Truck Index: 2; Value: Bus * /

In the above code, the each function is used to iterate over an array. The function has 2 required parameters... The first parameter is an entity (array or object), the elements (properties) of which must be iterated over. In this case, it is the arr array. The second parameter is a callback function that will be executed for each element (in this case) of the array. It has 2 parameters that are available inside it through the corresponding variables. The first parameter is the ordinal number of the element (counting is performed from 0). The second parameter is the value of the current array element.

Example # 2. In this example we will iterate over all the properties of the object.


// smartphone object with 5 properties var smartphone \u003d ("name": "LG G5 se", "year": "2016", "screen-size": "5.3", "screen-resolution": "2560 x 1440 "," os ":" Android 6.0 (Marshmallow) "); // iterate over the smartphone object $ .each (smartphone, function (key, value) (// actions that will be performed for each property of the object // key - the current name of the array property // value - the value of the current property of the object // display the name of the property and its value to the console console.log ("Property:" + key + "; Value:" + value);)); / * Result (in console): Property: name; Value: LG G5 se Property: year; Value: 2016 Property: screen-size; Value: 5.3 Property: screen-resolution; Value: 2560 x 1440 Property: os; Value: Android 6.0 (Marshmallow) * /

The each function can be used to iterate over JavaScript objects. The difference in its use is only that the parameters of the callback function have different values. The first parameter stores the name of the object property, and the second stores the value of this property.

Example # 3. In it, we will iterate over a more complex structure (let's see how to use nested each).

// an object consisting of 2 properties. Each property of this object has an array as its value, the elements of which are also objects var articles \u003d ("Bootstrap": [("id": "1", "title": "Introduction"), ("id": "2" , "title": "How to install"), ("id": "3", "title": "Grid")], "JavaScript": [("id": "4", "title": "Basics "), (" id ":" 5 "," title ":" Selection of elements ")]); $ .each (articles, function (key, data) (console.log ("Section:" + key); $ .each (data, function (index, value) (console.log ("Article: id \u003d" + value ["id"] + "; Title \u003d" + value ["title"]);));)); / * Result: Section: Bootstrap Article: id \u003d 1; Title \u003d Introduction Article: id \u003d 2; Title \u003d How to install Article: id \u003d 3; Title \u003d Grid Section: JavaScript Article: id \u003d 4; Title \u003d Basics Article: id \u003d 5; Name \u003d Selection of elements * /

How do I interrupt each (exit the loop)?

The each loop is interrupted with a return statement, which must return false.

For example, let us interrupt the execution of the each loop after we find the number 7 in the arr array:

// an array of 5 numbers var arr \u003d; // the number to find var find \u003d 7; // iterate over the arr array $ .each (arr, function (index, value) (// if the required number is found, then .. if (value \u003d\u003d\u003d find) (// print it to the console console.log ("Hurray! The number "+ find +" found! This number has an index: "+ index); // abort the loop execution return false;) else (// otherwise, print the current number to the console console.log (" Current number: "+ value); ))); / * Result (in console): Current number: 5 Current number: 4 Hooray! Number 7 found! This number has an index: 2 * /

How do I go to the next iteration (each continue)?

In each, the execution of the current iteration is interrupted and the transition to the next one is performed using the return statement, which must have a value other than false.

// an array of numbers var arr \u003d; // an array that must contain all elements of the arr array, except for even numbers var newarr \u003d; // iterate over the arr array $ .each (arr, function (index, value) (// if the element is even, then skip it if (value% 2 \u003d\u003d\u003d 0) (// interrupt the current iteration and go to the next one return; ) // add value to array newarr newarr.push (value);)); console.log ("Original array (arr):" + arr.join ()); console.log ("Result array (newarr):" + newarr.join ()); / * Result (in console): Original array (arr): 3,5,4,9,17,19,30,35,40 Result array (newarr): 3,5,9,17,19,35 * /

Iterating over current items (.each)

The syntax for the each method (applies only to selected elements):


.each (function); // function - a function that will be executed for each element of the current object

Let's see how the.each method works with the following example (iterating over div elements):


In the above example, the each method uses the current set (items selected with the $ ("div") selector). The each method handler is always a function that will be executed for each element of the current set (in this case, for each div element). This function has 2 optional parameters. One of them (index) is the sequence number of the current iteration, and the second (element) is the DOM reference to the current element. In addition, the this keyword is available inside the function, which, like the second parameter, contains a DOM reference to the current element.

For example, let's print to the console the value of the href attribute for all a elements on the page:

$ ("a"). each (function () (console.log ($ (this) .attr ("href"));));

$ ("a"). each (function () (var link \u003d $ (this) .attr ("href"); if ((link.indexOf ("http: //") \u003d\u003d 0) || (link .indexOf ("https: //") \u003d\u003d 0)) (console.log ("link href \u003d" + link);))); // If the page contains the following links: // Yandex // How does JavaScript work? // Bootstrap // Then in the console we will see the following result: // https://www.yandex.ru/ // http://getbootstrap.com/

For example, let's take a look at how to loop through each DOM element that has the class name (let's loop through all the elements of the same class).

Raspberry pi
single-board compute
Intel Galileo Gen2
19$
Pine A64 Plus

For example, let's figure out how to iterate over all the elements on a page.

For example, let's print the value of all input elements on the page.

$ ("input"). each (function () (console.log ($ (this) .val ());));

For example, let's iterate over all the children located in the ul with id \u003d "myList" (each children).

  • Html
  • JavaScript

Let's look at a way to determine the last index (element) in jQuery's each method.

// select items var myList \u003d $ ("ul li"); // determine the number of elements in the selection var total \u003d myList.length; // iterate over the selected elements myList.each (function (index) (if (index \u003d\u003d\u003d total - 1) (// this is the last element in the selection)));

Last update: 26.03.2018

The Array object represents an array and provides a number of properties and methods with which we can manipulate the array.

Array initialization

You can create an empty array using square brackets or the Array constructor:

Var users \u003d new Array (); var people \u003d; console.log (users); // Array console.log (people); // Array

You can immediately initialize the array with a number of elements:

Var users \u003d new Array ("Tom", "Bill", "Alice"); var people \u003d ["Sam", "John", "Kate"]; console.log (users); // ["Tom", "Bill", "Alice"] console.log (people); // ["Sam", "John", "Kate"]

You can define an array and define new elements in it along the way:

Var users \u003d new Array (); users \u003d "Tom"; users \u003d "Kate"; console.log (users); // "Tom" console.log (users); // undefined

It doesn't matter that by default the array is created with zero length. With the help of indices, we can substitute one or another element for a specific index in the array.

length

To find out the length of an array, use the length property:

Var fruit \u003d new Array (); fruit \u003d "apples"; fruit \u003d "pears"; fruit \u003d "plums"; document.write ("In the array fruit" + fruit.length + "of the element:
"); for (var i \u003d 0; i< fruit.length; i++) document.write(fruit[i] + "
");

In fact, the length of the array will be the index of the last element with the addition of one. For instance:

Var users \u003d new Array (); // there are 0 elements in the array users \u003d "Tom"; users \u003d "Kate"; users \u003d "Sam"; for (var i \u003d 0; i

Browser output:

Tom Kate undefined undefined Sam

Despite the fact that for indices 2 and 3 we did not add elements, but the length of the array in this case will be number 5. It's just that the elements with indices 2 and 3 will have the value undefined.

Copying an array. slice ()

Array copying can be shallow or deep copy.

With shallow copying, it is enough to assign the value to the variable to another variable that stores the array:

Var users \u003d ["Tom", "Sam", "Bill"]; console.log (users); // ["Tom", "Sam", "Bill"] var people \u003d users; // shallow copy people \u003d "Mike"; // change the second element console.log (users); // ["Tom", "Mike", "Bill"]

In this case, the people variable after copying will point to the same array as the users variable. Therefore, when the elements in people change, the elements in users also change, since in fact it is the same array.

This behavior is not always desirable. For example, we want the variables to point to separate arrays after copying. And in this case, deep copying can be used with the slice () method:

Var users \u003d ["Tom", "Sam", "Bill"]; console.log (users); // ["Tom", "Sam", "Bill"] var people \u003d users.slice (); // deep copy people \u003d "Mike"; // change the second element console.log (users); // ["Tom", "Sam", "Bill"] console.log (people); // ["Tom", "Mike", "Bill"]

In this case, after copying, the variables will point to different arrays, and we can change them separately from each other.

Also, the slice () method allows you to copy part of an array:

Var users \u003d ["Tom", "Sam", "Bill", "Alice", "Kate"]; var people \u003d users.slice (1, 4); console.log (people); // ["Sam", "Bill", "Alice"]

The slice () method is passed the start and end indices, which are used to fetch values \u200b\u200bfrom the array. That is, in this case, the selection into a new array goes from index 1 to index 4, not including. And since array indexing starts from zero, the second, third and fourth elements will appear in the new array.

push ()

The push () method adds an element to the end of the array:

Var fruit \u003d; fruit.push ("apples"); fruit.push ("pears"); fruit.push ("plums"); fruit.push ("cherry", "apricot
"); document.write (fruit); // apples, pears, plums, cherries, apricots

pop ()

The pop () method removes the last element from the array:

Var fruit \u003d ["apples", "pears", "plums"]; var lastFruit \u003d fruit.pop (); // fetch the last element from the array document.write (lastFruit + "
"); document.write (" In the array fruit "+ fruit.length +" of the element:
"); for (var i \u003d 0; i ");

Browser output:

Plums There are 2 elements in the fruit array: apples, pears

shift ()

The shift () method extracts and removes the first element from the array:

Var fruit \u003d ["apples", "pears", "plums"]; var firstFruit \u003d fruit.shift (); document.write (firstFruit + "
"); document.write (" In the array fruit "+ fruit.length +" of the element:
"); for (var i \u003d 0; i ");

Browser output:

Apples There are 2 elements in the fruit array: pears plums

unshift ()

The unshift () method adds a new element to the beginning of the array:

Var fruit \u003d ["apples", "pears", "plums"]; fruit.unshift ("apricots"); document.write (fruit);

Browser output:

Apricots, apples, pears, plums

Removing an element by index. splice ()

The splice () method removes elements from a specific index. For example, removing items from the third index:

Var users \u003d ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted \u003d users.splice (3); console.log (deleted); // ["Alice", "Kate"] console.log (users); // ["Tom", "Sam", "Bill"]

The slice method returns the removed elements.

In this case, the deletion goes from the beginning of the array. If you pass a negative index, then the deletion will be performed from the end of the array. For example, let's remove the last element:

Var users \u003d ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted \u003d users.splice (-1); console.log (deleted); // ["Kate"] console.log (users); // ["Tom", "Sam", "Bill", "Alice"]

An additional version of the method allows you to specify the ending index to delete. For example, let's remove from the first to the third index:

Var users \u003d ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted \u003d users.splice (1,3); console.log (deleted); // ["Sam", "Bill", "Alice"] console.log (users); // ["Tom", "Kate"]

Another version of the splice method allows you to insert new elements instead of the deleted elements:

Var users \u003d ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted \u003d users.splice (1,3, "Ann", "Bob"); console.log (deleted); // ["Sam", "Bill", "Alice"] console.log (users); // ["Tom", "Ann", "Bob", "Kate"]

In this case, we delete three elements from 1st to 3rd indices and insert two elements instead.

concat ()

The concat () method is used to concatenate arrays:

Var fruit \u003d ["apples", "pears", "plums"]; var vegetables \u003d ["tomatoes", "cucumbers", "potatoes"]; var products \u003d fruit.concat (vegetables); for (var i \u003d 0; i< products.length; i++) document.write(products[i] + "
");

Moreover, it is not necessary to combine only arrays of the same type. Different types are possible:

Var fruit \u003d ["apples", "pears", "plums"]; var prices \u003d; var products \u003d fruit.concat (prices);

join ()

The join () method concatenates all the elements of an array into one string:

Var fruit \u003d ["apples", "pears", "plums", "apricots", "peaches"]; var fruitString \u003d fruit.join (","); document.write (fruitString);

The join () method is passed a separator between the array elements. In this case, a comma and a space (",") will be used as a separator.

sort ()

The sort () method sorts the array in ascending order:

Var fruit \u003d ["apples", "pears", "plums", "apricots", "peaches"]; fruit.sort (); for (var i \u003d 0; i< fruit.length; i++) document.write(fruit[i] + "
");

Browser output:

Apricots pears peaches plums apples

reverse ()

The reverse () method reverses the array backwards:

Var fruit \u003d ["apples", "pears", "plums", "apricots", "peaches"]; fruit.reverse (); for (var i \u003d 0; i< fruit.length; i++) document.write(fruit[i] + "
");

Browser output:

Peaches apricots plums pears apples

Combined with the sort () method, you can sort the array in descending order:

Var fruit \u003d ["apples", "pears", "plums", "apricots", "peaches"]; fruit.sort (). reverse (); for (var i \u003d 0; i< fruit.length; i++) document.write(fruit[i] + "
");

Browser output:

Apples plums peaches pears apricots

Finding the index of an element

The indexOf () and lastIndexOf () methods return the index of the first and last included element in the array. For instance:

Var fruit \u003d ["apples", "pears", "plums", "apples", "pears"]; var firstIndex \u003d fruit.indexOf ("apples"); var lastIndex \u003d fruit.lastIndexOf ("apples"); var otherIndex \u003d fruit.indexOf ("cherries"); document.write (firstIndex); // 0 document.write (lastIndex); // 3 document.write (otherIndex); // -1

firstIndex has a value of 0, since the first inclusion of the "apples" in the array falls on index 0, and the last one on index 3.

If the element is not in the array, then the indexOf () and lastIndexOf () methods return -1.

every ()

The every () method checks if all elements meet a certain condition:

Var numbers \u003d [1, -12, 8, -4, 25, 42]; function condition (value, index, array) (var result \u003d false; if (value\u003e 0) (result \u003d true;) return result;); var passed \u003d numbers.every (condition); document.write (passed); // false

The every () method is passed a function representing the condition as a parameter. This function takes three parameters:

Function condition (value, index, array) ()

The value parameter represents the currently iterated over element of the array, the index parameter represents the index of that element, and the array parameter passes a reference to the array.

In this function, we can check the passed element value for compliance with some condition. For example, in this example, we check each element of the array to see if it is greater than zero. If more, then return true, that is, the element meets the condition. If less, then we return false - the element does not match the condition.

As a result, when the numbers.every (condition) method is called, it iterates over all the elements of the numbers array and passes them in turn to the condition function. If this function returns true for all elements, then every () method returns true. If at least one element does not match the condition, then the every () method returns false.

some ()

The some () method is similar to the every () method, except that it checks if at least one item matches a condition. And in this case, the some () method returns true. If there are no elements matching the condition in the array, then the value false is returned:

Var numbers \u003d [1, -12, 8, -4, 25, 42]; function condition (value, index, array) (var result \u003d false; if (value \u003d\u003d\u003d 8) (result \u003d true;) return result;); var passed \u003d numbers.some (condition); // true

filter ()

The filter () method, like some () and every (), accepts a condition function. But at the same time it returns an array of those elements that meet this condition:

Var numbers \u003d [1, -12, 8, -4, 25, 42]; function condition (value, index, array) (var result \u003d false; if (value\u003e 0) (result \u003d true;) return result;); var filteredNumbers \u003d numbers.filter (condition); for (var i \u003d 0; i< filteredNumbers.length; i++) document.write(filteredNumbers[i] + "
");

Browser output:

1 8 25 42

forEach () and map ()

The forEach () and map () methods iterate over the elements and perform certain operations on them. For example, you can use the following code to calculate the squares of numbers in an array:

Var numbers \u003d [1, 2, 3, 4, 5, 6]; for (var i \u003d 0; i "); }

But using the forEach () method, you can simplify this construction:

Var numbers \u003d [1, 2, 3, 4, 5, 6]; function square (value, index, array) (var result \u003d value * value; document.write ("The square of the number" + value + "is" + result + "
");); numbers.forEach (square);

The forEach () method takes the same function as a parameter, into which, when iterating over the elements, the current iterable element is passed and operations are performed on it.

The map () method is similar to the forEach method, it also accepts a function as a parameter to perform operations on iterable array elements, but the map () method returns a new array with the results of operations on array elements.

For example, let's use the map method to calculate the squares of array numbers:

Var numbers \u003d [1, 2, 3, 4, 5, 6]; function square (value, index, array) (return result \u003d value * value;); var squareArray \u003d numbers.map (square); document.write (squareArray);

The function that is passed to the map () method receives the current iterable element, performs operations on it, and returns some value. This value is then passed into the resulting squareArray.