js实现foreach

实现 forEach 方法
在 JavaScript 中,Array.prototype.forEach 是一个常用的数组遍历方法。以下是几种实现方式:
基本实现
Array.prototype.myForEach = function(callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
带 thisArg 的实现
Array.prototype.myForEach = function(callback, thisArg) {
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
使用 reduce 实现
Array.prototype.myForEach = function(callback) {
this.reduce((_, current, index, array) => {
callback(current, index, array);
}, null);
};
注意事项
- 原生的
forEach不能中断遍历(没有类似break的功能) - 实现时需要考虑稀疏数组的处理
- 回调函数的参数顺序是 (元素, 索引, 数组本身)
使用示例
const arr = [1, 2, 3];
arr.myForEach((item, index) => {
console.log(`索引 ${index} 的值是 ${item}`);
});
这些实现方式展示了 forEach 方法的核心功能,可以根据具体需求进行调整。







