JavaScript 数组的 forEach() 方法详解
forEach()
方法对数组的每个元素执行提供的函数。
示例
let numbers = [1, 3, 4, 9, 8];
// 计算每个数字的平方的函数
function computeSquare(element) {
console.log(element * element);
}
// 计算每个元素的平方根
numbers.forEach(computeSquare);
/* 输出:
1
9
16
81
64
*/
forEach() 语法
forEach()
方法的语法为:
arr.forEach(callback(currentValue), thisArg);
这里,arr 是一个数组。
forEach() 参数
forEach()
方法接受:
-
callback - 对每个数组元素执行的函数。它接受:
-
currentValue - 数组中传递的当前元素。
thisArg(可选)- 执行回调时使用的 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 不会对没有值的元素执行
// 在这个例子中,它跳过了第三个元素,因为它是空的
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
方法定义内。
推荐阅读: JavaScript 数组 map()