js实现foreach功能
实现 forEach 功能的方法
在 JavaScript 中,Array.prototype.forEach 是一个常用的方法,用于遍历数组的每个元素并执行回调函数。以下是几种实现类似功能的方法:
使用原生 forEach
const arr = [1, 2, 3];
arr.forEach((item, index) => {
console.log(`Item: ${item}, Index: ${index}`);
});
手动实现 forEach
可以通过扩展 Array.prototype 或直接编写一个函数来实现类似的功能:
function customForEach(array, callback) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
const arr = [1, 2, 3];
customForEach(arr, (item, index) => {
console.log(`Item: ${item}, Index: ${index}`);
});
使用 for...of 循环
const arr = [1, 2, 3];
for (const [index, item] of arr.entries()) {
console.log(`Item: ${item}, Index: ${index}`);
}
使用 map 方法
虽然 map 主要用于生成新数组,但也可以用于遍历:
const arr = [1, 2, 3];
arr.map((item, index) => {
console.log(`Item: ${item}, Index: ${index}`);
});
使用 reduce 方法
reduce 也可以模拟 forEach 的功能:

const arr = [1, 2, 3];
arr.reduce((_, item, index) => {
console.log(`Item: ${item}, Index: ${index}`);
}, null);
注意事项
forEach无法通过return或break中断循环,如果需要中断,可以使用for循环或some/every方法。- 手动实现时需注意回调函数的参数顺序(当前元素、索引、原数组)。






