js实现foreach
实现 forEach 方法
在 JavaScript 中,forEach 是数组的原生方法,用于遍历数组的每个元素并执行回调函数。以下是手动实现 forEach 的方法:

Array.prototype.myForEach = function(callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
使用示例
const arr = [1, 2, 3];
arr.myForEach((item, index, array) => {
console.log(`元素: ${item}, 索引: ${index}, 数组: ${array}`);
});
实现说明
- 方法接收一个回调函数作为参数
- 回调函数接收三个参数:当前元素、当前索引和原数组
- 使用
for循环遍历数组 - 在每次迭代中调用回调函数
注意事项
- 原生
forEach方法不会改变原数组 - 手动实现的版本也应保持这一特性
- 回调函数中的
this默认指向全局对象,可以使用第二个参数绑定上下文
绑定 this 的版本
Array.prototype.myForEach = function(callback, thisArg) {
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
性能考虑
- 原生
forEach通常比手动实现的版本性能更好 - 在需要中断循环的场景下,
for循环或some/every方法可能更合适






