js foreach 实现
forEach 的基本用法
在 JavaScript 中,forEach 是数组对象的一个方法,用于遍历数组的每个元素并执行回调函数。语法如下:
array.forEach(function(currentValue, index, array) {
// 执行操作
}, thisArg);
currentValue:当前处理的数组元素。index(可选):当前元素的索引。array(可选):正在遍历的数组。thisArg(可选):回调函数中的this值。
简单示例
以下是一个简单的示例,展示如何使用 forEach 遍历数组并打印每个元素:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
输出:

1
2
3
4
5
使用箭头函数
可以使用箭头函数简化回调函数的写法:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
访问索引和原数组
回调函数可以接收索引和原数组作为参数:

const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit, index, array) => {
console.log(`Element ${fruit} is at index ${index} in array ${array}`);
});
修改原数组
forEach 不会直接修改原数组,但可以通过回调函数修改原数组的值:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index, array) => {
array[index] = number * 2;
});
console.log(numbers); // [2, 4, 6, 8, 10]
使用 thisArg
可以通过 thisArg 参数指定回调函数中的 this 值:
function Counter() {
this.count = 0;
}
Counter.prototype.increment = function(array) {
array.forEach(function(element) {
this.count++;
}, this);
};
const counter = new Counter();
counter.increment([1, 2, 3]);
console.log(counter.count); // 3
注意事项
forEach无法中断或跳出循环(除非抛出异常)。如果需要提前终止循环,可以使用for循环或Array.prototype.some、Array.prototype.every。forEach不会为稀疏数组中缺失的元素执行回调函数。forEach不会返回任何值,仅用于遍历数组。






