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.

句法

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
					

参数

callback

Function to execute on each element. It accepts between one and three arguments:

currentValue

The current element being processed in the array.

index 可选
The index currentValue in the array.
array 可选
The array forEach() was called upon.
thisArg 可选
Value to use as this when executing callback .

返回值

undefined .

描述

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, see example below .)

callback is invoked with three arguments:

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

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() ,和 findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

forEach expects a synchronous function

forEach does not wait for promises. Kindly make sure you are aware of the implications while using promises(or async functions) as forEach callback.
范例代码
let ratings = [5, 4, 5];
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)
// Naively expected output: 14
// Actual output: 0
					

范例

No operation for uninitialized values (sparse arrays)

const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach((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 copyItems = []
// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i])
}
// after
items.forEach(function(item){
  copyItems.push(item)
})
					

Printing the contents of an array

注意: 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...
[2, 5, , 9].forEach(logArrayElements)
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 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((entry) => {
    this.sum += entry
    ++this.count
  }, this)
  // ^---- Note
}
const obj = new Counter()
obj.add([2, 5, 9])
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 值。

注意: If passing the callback function uses an 箭头函数表达式 thisArg parameter can be omitted, since all arrow functions lexically bind the this 值。

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

Modifying the array during iteration

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((word) => {
  console.log(word)
  if (word === 'two') {
    words.shift() //'one' will delete from array
  }
}) // one // two ​​​​// four
console.log(words);  //['two', 'three',​​​​ '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() .

function flatten(arr) {
  const result = []
  arr.forEach((i) => {
    if (Array.isArray(i)) {
      result.push(...flatten(i))
    } else {
      result.push(i)
    }
  })
  return result
}
// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Array.prototype.forEach' in that specification.

浏览器兼容性

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. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
forEach Chrome 1 Edge 12 Firefox 1.5 IE 9 Opera 9.5 Safari 3 WebView Android ≤37 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. Array
  3. 特性
    1. Array.prototype.length
    2. Array.prototype[@@unscopables]
  4. 方法
    1. Array.from()
    2. Array.isArray()
    3. Array.of()
    4. Array.prototype.concat()
    5. Array.prototype.copyWithin()
    6. Array.prototype.entries()
    7. Array.prototype.every()
    8. Array.prototype.fill()
    9. Array.prototype.filter()
    10. Array.prototype.find()
    11. Array.prototype.findIndex()
    12. Array.prototype.flat()
    13. Array.prototype.flatMap()
    14. Array.prototype.forEach()
    15. Array.prototype.includes()
    16. Array.prototype.indexOf()
    17. Array.prototype.join()
    18. Array.prototype.keys()
    19. Array.prototype.lastIndexOf()
    20. Array.prototype.map()
    21. Array.prototype.pop()
    22. Array.prototype.push()
    23. Array.prototype.reduce()
    24. Array.prototype.reduceRight()
    25. Array.prototype.reverse()
    26. Array.prototype.shift()
    27. Array.prototype.slice()
    28. Array.prototype.some()
    29. Array.prototype.sort()
    30. Array.prototype.splice()
    31. Array.prototype.toLocaleString()
    32. Array.prototype.toSource()
    33. Array.prototype.toString()
    34. Array.prototype.unshift()
    35. Array.prototype.values()
    36. Array.prototype[@@iterator]()
    37. get Array[@@species]
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()