JavaScript Array forEach()

forEach() 方法为每个 数组 元素执行一个提供的函数。

示例

let numbers = [1, 3, 4, 9, 8];

// function to compute square of each number
function computeSquare(element) {
  console.log(element * element);
}

// compute square root of each element numbers.forEach(computeSquare);
/* Output: 1 9 16 81 64 */

forEach() 语法

forEach() 方法的语法是:

arr.forEach(callback(currentValue), thisArg)

这里,arr 是一个数组。


forEach() 参数

forEach() 方法接受

  • callback - 要对每个数组元素执行的 回调函数。它接受
    • currentValue - 从数组中传递的当前元素。
  • thisArg(可选)- 在执行 callback 时用作 this 的值。默认值为 undefined

forEach() 返回值

  • 返回 undefined

注意事项:

  • forEach() 不会改变原始数组。
  • forEach() 按顺序为每个数组元素执行一次 callback
  • forEach() 不会为没有值的数组元素执行 callback

示例 1:打印数组内容

function printElements(element, index) {
    console.log('Array Element ' + index + ': ' + element);
}

const prices = [1800, 2000, 3000, , 5000, 500, 8000];

// forEach does not execute for elements without values
// in this case, it skips the third element as it is empty
prices.forEach(printElements);

输出

Array Element 0: 1800
Array Element 1: 2000
Array Element 2: 3000
Array Element 4: 5000
Array Element 5: 500
Array Element 6: 8000

示例 2:使用 thisArg

function Counter() {
    this.count = 0;
    this.sum = 0;
    this.product = 1;
}

Counter.prototype.execute = function (array) {
array.forEach((entry) => { this.sum += entry; ++this.count; this.product *= entry; }, this)
} const obj = new Counter(); obj.execute([4, 1, , 45, 8]); console.log(obj.count); // 4 console.log(obj.sum); // 58 console.log(obj.product); // 1440

输出

4
58
1440

这里,我们可以再次看到 forEach 跳过了空元素。thisArg 作为 this 传递到 Counter 对象 execute 方法的定义中。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战