js foreach 实现
forEach 的基本用法
Array.prototype.forEach 是 JavaScript 中用于遍历数组的方法,接受一个回调函数作为参数,对数组的每个元素执行该函数。
const array = [1, 2, 3];
array.forEach((element, index, array) => {
console.log(element, index, array);
});
实现自定义 forEach
可以通过扩展 Array.prototype 或独立函数实现类似 forEach 的功能。
function customForEach(array, callback) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
const numbers = [10, 20, 30];
customForEach(numbers, (num, index) => {
console.log(`Element at ${index} is ${num}`);
});
原型链扩展实现
在 Array.prototype 上添加方法,模拟原生 forEach 的行为。
Array.prototype.myForEach = function(callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
const fruits = ['apple', 'banana', 'cherry'];
fruits.myForEach((fruit, idx) => {
console.log(`${idx + 1}: ${fruit}`);
});
处理稀疏数组
原生 forEach 会跳过空元素,自定义实现时可通过 hasOwnProperty 检查。
Array.prototype.sparseForEach = function(callback) {
for (let i = 0; i < this.length; i++) {
if (this.hasOwnProperty(i)) {
callback(this[i], i, this);
}
}
};
const sparseArray = [1, , 3];
sparseArray.sparseForEach(item => console.log(item)); // 只输出 1 和 3
终止遍历的变通方案
原生 forEach 不能通过 break 终止,但可以通过抛出异常或使用 some/every 替代。
const data = [1, 2, 3, 4, 5];
try {
data.forEach(item => {
if (item > 3) throw new Error('BreakLoop');
console.log(item);
});
} catch (e) {
if (e.message !== 'BreakLoop') throw e;
}
性能注意事项
在大型数组或性能敏感场景中,传统 for 循环通常比 forEach 更快,但可读性较差。

const bigArray = new Array(1000000).fill(0);
console.time('forEach');
bigArray.forEach(x => x * 2);
console.timeEnd('forEach');
console.time('for loop');
for (let i = 0; i < bigArray.length; i++) {
bigArray[i] * 2;
}
console.timeEnd('for loop');






