JavaScript Glossary: Array .forEach() Method

Publikováno: 8.2.2019

Basics

The forEach() method takes a function that performs an action on each of the elements in this array.

[1, 2, 3, 4, 5].forEach(functio...

Celý článek

Basics

The forEach() method takes a function that performs an action on each of the elements in this array.

[1, 2, 3, 4, 5].forEach(function(number){
    console.log(number * 2)
})

https://scotch.io/embed/gist/8a2c8d841f52964a1929656b80729dc2

Syntax

array.forEach(callback[, thisArg])

2 Parameters

callback This is the function which performs an action on each element. This function can take three parameters.

  • value: the value currently being processed in the array.
  • index: this is the index of the value being processed - optional.
  • array: this is the parent array running the forEach method - optional.

thisArg This is an optional value to be used as the this value for the array - optional

Returns undefined

The method returns undefined and doesn't mutate the original calling array.

const names = ['Johnny', 'Pete', 'Sammy']

names.forEach(name => {
  doSomethingWithName(name);
})

Common Uses and Snippets

Copying the contents of one array array to another

The forEach method can be used to copy the content of an array into a new array. Several ways exist to do this but the forEach method affords the ability to modify each element before being copied.

https://scotch.io/embed/gist/a382148a5154897466526cc5ba73d22c

Replacing the forloop

Using the forEach method in place of a for loop. Since it has a simpler syntax, it is mostly used in place of a regular for loop.

https://scotch.io/embed/gist/9c3a886247f2da58f64034426e5aa969

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace