Foreach js for arrays and collections. How to create an associative array in JavaScript. Explicit use of iterator

💖 Do you like it? Share the link with your friends

Definition and Application

JavaScript method forEach() allows you to execute the passed function once for each element in the array in ascending index order.

Please note that the callback function passed as a method parameter forEach() will not be called for deleted or missing array elements.

Range of elements processed using the method forEach() installed in front first calling the callback function. If elements were added to the array after its call, then the function will not be called on such elements.

If the values ​​of existing array elements change at the time of execution, then the value passed to the function will be the value at the time when the method forEach() visits them. If elements are deleted before they are visited, then such elements will not be visited. If elements that have already been visited are removed while traversing the array, then later elements will be skipped.

Browser support

Method
Opera

IExplorer

edge
forEach() YesYesYesYes9.0 Yes

JavaScript syntax:

// only with callback function array.forEach(function ( currentValue, index, arr)); // using an object that can be referenced by the this keyword array.forEach(function ( currentValue, index, arr), thisValue);

JavaScript version

ECMAScript 5.1 (Implemented in JavaScript 1.6)

Parameter values

ParameterDescription
function Callback function to be executed one times for each element in the array. The function accepts the following parameters:
  • currentValue - value of the current element
  • index - array index of the current element.
  • arr - the array to which the current element belongs (through which the passage occurs).

If something is passed as a parameter to a method that is not a function object, an exception will be thrown TypeError. Required parameter.

thisValue An object that can be referenced by the this keyword inside the callback function. If the parameter thisValue is not used, then undefined will be used as the value of this (ultimately this will depend on the normal rules of the function's execution context). Optional parameter.

Usage example

In the following example, we will look at how to get the sum of all the elements of an array using JavaScript method forEach():

var array = ; var sum = 0 ; // initialize a variable containing a numeric value array.forEach( // loop through all elements of array function sumNumber( currentValue) { sum += currentValue; ) ); console .log( sum); // display the value of the sum variable equal to 50

In the following example we will look at using second method argument forEach(), which points to an object that we can reference using keyword this inside the callback function:

var numbers = ; // initialize a variable containing an array of numeric values var squared = ; // initialize a variable containing an empty array var myObject = ( // initialize the variable containing the object square:function( currentValue) { // object method that takes a value return currentValue * currentValue; // and returns it squared } } ; numbers.forEach( // loop through all elements of the numbers array function( currentValue) { squared.push(this .square( currentValue)); // add the return value of the square method of the myObject object to the squared array } , myObject // the object we refer to using the this keyword); console .log( squared); // display the value of the squared variable equal to ;
  • I. Iterating over real arrays
    1. forEach method and related methods
    2. for loop
    3. Proper use of the for...in loop
    4. for...of loop (implicit use of iterator)
    5. Explicit use of iterator
  • II. Iterating over array-like objects
    1. Using methods to iterate over real arrays
    2. Convert to a real array
    3. A note on runtime objects

I. Iterating over real arrays

On this moment There are three ways to iterate over the elements of a real array:

  1. method Array.prototype.forEach ;
  2. classic for loop
  3. a “correctly” constructed for...in loop.

In addition, soon, with the advent of the new ECMAScript 6 (ES 6) standard, two more methods are expected:

  1. for...of loop (implicit use of iterator);
  2. explicit use of iterator.

1. The forEach method and related methods

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

Usage example:

Var a = ["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 natively support this method. These include IE 8 and above early versions, which are still in use here and there.

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 possible cost of calling a callback on each element, don't worry and read this.

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

  • every - returns true if for each element of the array the callback returns a value that can be converted to true .
  • some - returns true if for at least one element of the array the callback returns a value that can be converted to true.
  • filter - creates a new array that includes those elements of the original array for which the callback returns true .
  • map - creates a new array consisting of the values ​​returned by the callback.
  • reduce - reduces an array to a single value, applying a callback to each element of the array in turn, starting with the first (can be useful for calculating the sum of array elements and other summary functions).
  • reduceRight - works similar to reduce, but iterates through elements in reverse order.

2. For loop

Good old for rules:

Var a = ["a", "b", "c"]; var index; for (index = 0; index< a.length; ++index) { console.log(a); }

If the length of the array is constant throughout the loop, and the loop itself belongs to a performance-critical section of code (which is unlikely), then you can use a “more optimal” version of for that stores the length of the array:

Var a = ["a", "b", "c"]; var index, len; for (index = 0, len = a.length; index< len; ++index) { console.log(a); }

In theory, this code should run a little faster than the previous one.

If the order of the elements 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, changing the order of the search to the reverse:

Var a = ["a", "b", "c"]; var index; for (index = a.length - 1; index >= 0; --index) ( console.log(a); )

However, in modern JavaScript engines such optimization 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 a common misconception, the for...in loop does not iterate over array indices, but rather through enumerable properties of an object.

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

// a - sparse array var a = ; a = "a"; a = "b"; a = "c"; for (var key in a) ( if (a.hasOwnProperty(key) && /^0$|^d*$/.test(key) && key<= 4294967294) { console.log(a); } }

In this example, two checks are performed at each iteration of the loop:

  1. that the array has its own property called key (not inherited from its prototype).
  2. that key is a string containing the decimal representation 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, which shows that the highest index an element in an array can have is: (2^32 - 2) = 4294967294 .

Of course, such checks will take up unnecessary 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. So, in the example above, only 3 iterations will be performed (for indexes 0, 10 and 10000) - versus 10001 in the for loop.

In order not to write such a cumbersome check code every time you need to iterate through an array, you can write 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 check code discussed above is universal, suitable for all cases. But instead, you can use a shorter version, although formally not entirely correct, but nevertheless suitable for most cases:

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

4. For...of loop (implicit use of iterator)

ES6, still in draft status, should introduce iterators to JavaScript.

Iterator is a protocol implemented by an object that defines a standard way to obtain a sequence of values ​​(finite or infinite).
An object has an iterator if it defines a next() method, a no-argument function that returns an object with two properties:

  1. done (boolean) - true if the iterator has reached the end of the iterable sequence. Otherwise the value is false .
  2. value - defines the value returned by the iterator. May be undefined (missing) if the done property is true .

Many built-in objects, incl. real arrays have iterators by default. The simplest way to use an iterator on real arrays is to use the new for...of construct.

Example of using for...of:

Varval; var a = ["a", "b", "c"]; for (val of a) ( console.log(val); )

In the example above, the for...of loop implicitly calls the Array object's iterator to obtain each value of the array.

5. Explicit use of 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 something like this:

Var a = ["a", "b", "c"]; var entry; while (!(entry = a.next()).done) ( console.log(entry.value); )

II. Iterating over array-like objects

In addition to real arrays, in JavaScript there are also 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 that correspond 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 to iterate over real arrays

At least most, if not all, methods for 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 real arrays.

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

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

Array.prototype.forEach.call(node.childNodes, function(child) ( // do something with the child object));

For the convenience of reusing this trick, you can declare a reference to the Array.prototype.forEach method in a separate variable and use it as a shorthand:

// (Assuming all code below is in the same scope) var forEach = 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 methods discussed above to iterate over real arrays. For conversion, you can use the generic method Array.prototype.slice , which can be applied to any array-like object. This is done very simply, as shown in the example below:

Var trueArray = Array.prototype.slice.call(arrayLikeObject, 0);

For example, if you want to convert a NodeList collection into a real array, you would need code like this:

Var divs = Array.prototype.slice.call(document.querySelectorAll("div"), 0);

3. A note on runtime objects

If you apply Array.prototype methods to runtime objects (such as DOM collections), then you should be aware that these methods are not guaranteed to work correctly in all runtimes (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 that object. The problem is that the ES5 standard itself allows for the possibility of an object misbehaving with respect to this operation (see §8.6.2).

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

  • I. Iterating over real arrays
    1. forEach method and related methods
    2. for loop
    3. Proper use of the for...in loop
    4. for...of loop (implicit use of iterator)
    5. Explicit use of iterator
    1. Using methods to iterate over real arrays
    2. Convert 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. method Array.prototype.forEach ;
  2. classic for loop
  3. a “correctly” constructed for...in loop.
In addition, soon, with the advent of the new ECMAScript 6 (ES 6) standard, two more methods are expected:
  1. for...of loop (implicit use of iterator);
  2. explicit use of iterator.

1. The forEach method and related methods

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

Usage example:
var a = ["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 natively support this method. These include IE 8 and earlier, which are still in use in some places.

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 possible cost of calling a callback on each element, don't worry and read this.

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

  • every - returns true if for each element of the array the callback returns a value that can be converted to true .
  • some - returns true if for at least one element of the array the callback returns a value that can be converted to true.
  • filter - creates a new array that includes those elements of the original array for which the callback returns true .
  • map - creates a new array consisting of the values ​​returned by the callback.
  • reduce - reduces an array to a single value, applying a callback to each element of the array in turn, starting with the first (can be useful for calculating the sum of array elements and other summary functions).
  • reduceRight - works similar to reduce, but iterates through elements in reverse order.

2. For loop

Good old for rules:

Var a = ["a", "b", "c"]; var index; for (index = 0; index< a.length; ++index) { console.log(a); }
If the length of the array is constant throughout the loop, and the loop itself belongs to a performance-critical section of code (which is unlikely), then you can use a “more optimal” version of for that stores the length of the array:

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

If the order of the elements 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, changing the order of the search to the reverse:

Var a = ["a", "b", "c"]; var index; for (index = a.length - 1; index >= 0; --index) ( console.log(a); )
However, in modern JavaScript engines such optimization 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 a common misconception, the for...in loop does not iterate over array indices, but rather through enumerable properties of an object.

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

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

  1. that the array has its own property called key (not inherited from its prototype).
  2. that key is a string containing the decimal representation 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, which shows that the highest index an element in an array can have is: (2^32 - 2) = 4294967294 .
Of course, such checks will take up unnecessary 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. So, in the example above, only 3 iterations will be performed (for indexes 0, 10 and 10000) - versus 10001 in the for loop.

In order not to write such a cumbersome check code every time you need to iterate through an array, you can write 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 check code discussed above is universal, suitable for all cases. But instead, you can use a shorter version, although formally not entirely correct, but nevertheless suitable for most cases:

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

4. For...of loop (implicit use of iterator)

ES6, still in draft status, should introduce iterators to JavaScript.

Iterator is a protocol implemented by an object that defines a standard way to obtain a sequence of values ​​(finite or infinite).
An iterator is an object that defines a next() method - a no-argument function that returns an object with two properties:

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

Example of using for...of:

Varval; var a = ["a", "b", "c"]; for (val of a) ( console.log(val); )
In the example above, the for...of loop implicitly calls the Array object's iterator to obtain each value of the array.

5. Explicit use of 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 something like this:

Var a = ["a", "b", "c"]; var it = a.entries(); var entry; while (!(entry = 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 ​​of the array. At each iteration, entry.value contains an array of the form [key, value] .

II. Iterating over array-like objects

In addition to real arrays, in JavaScript there are also 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 that correspond 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 to iterate over real arrays

At a minimum, 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 real arrays.

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

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

Array.prototype.forEach.call(node.childNodes, function(child) ( // do something with the child object));
To make this trick easier to reuse, you can declare a reference to the Array.prototype.forEach method in a separate variable and use it as a shortcut:

// (Assuming all code below is in the same scope) var forEach = Array.prototype.forEach; // ... forEach.call(node.childNodes, function(child) ( // do something with the child object));
If an array-like object has an iterator, 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 into a real array and use any of the methods discussed above for iterating 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 = Array.prototype.slice.call(arrayLikeObject, 0);
For example, if you wanted to convert a NodeList collection into an actual array, you'd need code something like this:

Var divs = 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 visual 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 be aware that these methods are not guaranteed to work correctly in all runtime environments (including browsers). This depends on the behavior of a particular object in a particular execution environment, or more precisely, on how the abstract operation HasProperty is implemented in this object. The problem is that the ES5 standard itself allows for the possibility of an object misbehaving with respect to this operation (see §8.6.2).

Therefore, it is important to test the operation of the Array.prototype methods in each runtime environment (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 is 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 ​​(sparse arrays)

const arraySparse = let numCallbackRuns = 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 = ["item1", "item2", "item3"] const copy = // before for (let i = 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 + "] = " + element) ) // Notice that index 2 is skipped, since there is no item at // that position in the array... .forEach(logArrayElements) // logs: // a = 2 // a = 5 // a = 9

Using thisArg

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

Function Counter() ( this.sum = 0 this.count = 0 ) Counter.prototype.add = function(array) ( array.forEach(function(entry) ( this.sum += entry ++this.count ), this ) // ^---- Note ) const obj = 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 = Object.create(Object.getPrototypeOf(obj)) const propNames = Object.getOwnPropertyNames(obj) propNames.forEach(function(name) ( const desc = Object.getOwnPropertyDescriptor(obj, name) Object .defineProperty(copy, name, desc) )) return copy ) const obj1 = ( a: 1, b: 2 ) const obj2 = 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 "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 = ["one", "two", "three", "four"] words.forEach(function(word) ( console.log(word) if (word === "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 = arr.forEach((i) => ( if (Array. isArray(i)) ( result.push(...flatten(i)) ) else ( result.push(i) )) return result ) // Usage const problem = , 8, 9]] flatten(problem) / /

Note on using Promises or async functions

let ratings = let sum = 0 let sumFunction = async function (a, b) ( return a + b ) ratings.forEach(async function(rating) ( sum = 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

Last update: 03/26/2018

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

Initializing an Array

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

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

You can immediately initialize an array with a certain number of elements:

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

You can define an array and add new elements to it as you go:

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

It does not matter that by default the array is created with zero length. Using indexes, we can substitute one or another element in an array at a specific index.

length

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

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

In fact, the length of the array will be the index of the last element plus one. For example:

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

Browser output:

Tom Kate undefined undefined Sam

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

Copying an array. slice()

Copying an array can be shallow or shallow (shallow copy) and deep (deep copy).

For shallow copying, it is enough to assign a variable the value of another variable that stores an array:

Var users = ["Tom", "Sam", "Bill"]; console.log(users); // ["Tom", "Sam", "Bill"] var people = users; // shallow copying people = "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 changing the elements in people, the elements in users will 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, you can use deep copying using the slice() method:

Var users = ["Tom", "Sam", "Bill"]; console.log(users); // ["Tom", "Sam", "Bill"] var people = users.slice(); // deep copy people = "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.

The slice() method also allows you to copy part of an array:

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

The slice() method is passed the starting and ending indexes, which are used to retrieve values ​​from the array. That is, in this case, the selection into the new array goes from index 1 to index 4, not including. And since array indexing starts from zero, the new array will contain the second, third, and fourth elements.

push()

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

Var fruit = ; 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 = ["apples", "pears", "plums"]; var lastFruit = fruit.pop(); // extract the last element from the array document.write(lastFruit + "
"); document.write("In the array fruit " + fruit.length + " element:
"); for(var i=0; i ");

Browser output:

Plums The fruit array has 2 elements: apples pears

shift()

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

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

Browser output:

Apples The fruit array has 2 elements: pears plums

unshift()

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

Var fruit = ["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 at a specific index. For example, removing elements from the third index:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = 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 occurs 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 = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = 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 for deletion. For example, let's delete the first to third index:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = 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 deleted elements:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = 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 the 1st to 3rd indices and insert two elements instead.

concat()

The concat() method is used to combine arrays:

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

In this case, it is not necessary to combine only arrays of the same type. Various types are possible:

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

join()

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

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

The join() method is passed the separator between 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 = ["apples", "pears", "plums", "apricots", "peaches"]; fruit.sort(); for(var i=0; i< fruit.length; i++) document.write(fruit[i] + "
");

Output in browser:

Apricots pears peaches plums apples

reverse()

The reverse() method reverses the array backwards:

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

Output in browser:

Peaches apricots plums pears apples

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

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

Output in browser:

Apples plums peaches pears apricots

Finding an element's index

The indexOf() and lastIndexOf() methods return the index of the first and last inclusion of an element in the array. For example:

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

firstIndex has a value of 0 because the first inclusion of the "apples" line in the array is at index 0, and the last is at index 3.

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

every()

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

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value > 0) ( result = true; ) return result; ); var passed = 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 current array element being iterated, 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 it is greater, then we return the value true , that is, the element meets the condition. If less, then return false - the element does not meet the condition.

As a result, when the numbers.every(condition) method is called, it iterates through all the elements of the numbers array and passes them one by one to the condition function. If this function returns true for all elements, then the 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, only it checks whether at least one element matches a condition. And in this case, the some() method returns true . If there are no elements matching the condition in the array, false is returned:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value === 8) ( result = true; ) return result; ); var passed = 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 = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value > 0) ( result = true; ) return result; ); var filteredNumbers = numbers.filter(condition); for(var i=0; i< filteredNumbers.length; i++) document.write(filteredNumbers[i] + "
");

Output in browser:

1 8 25 42

forEach() and map()

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

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

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

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

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

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

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

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

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



tell friends