js foreach 实现
使用 Array.prototype.forEach 方法
forEach 是 JavaScript 数组的原生方法,用于遍历数组的每个元素并执行回调函数。其语法如下:
array.forEach(function(currentValue, index, array) {
// 执行操作
}, thisArg);
currentValue:当前处理的数组元素。index(可选):当前元素的索引。array(可选):正在遍历的数组。thisArg(可选):回调函数中的this值。
示例:
const numbers = [1, 2, 3];
numbers.forEach(function(number) {
console.log(number * 2);
});
// 输出:2, 4, 6
手动实现 forEach 方法
如果需要手动实现 forEach,可以通过扩展 Array.prototype 或编写独立函数来实现:
function myForEach(array, callback, thisArg) {
for (let i = 0; i < array.length; i++) {
callback.call(thisArg, array[i], i, array);
}
}
const numbers = [1, 2, 3];
myForEach(numbers, function(number) {
console.log(number * 2);
});
// 输出:2, 4, 6
注意事项
forEach不会改变原数组,但回调函数可以修改数组元素。forEach无法通过return或break中断遍历,如果需要中断,建议使用for循环或Array.prototype.some/every。forEach会跳过空位(稀疏数组的空元素)。
示例(稀疏数组):
const sparseArray = [1, , 3];
sparseArray.forEach(function(item) {
console.log(item);
});
// 输出:1, 3






