手写 forEach
1. 在循环时,使用 while 的效率要比 for 高,因此尽量采用 while 循环:
Array.prototype.myforEach = function (callback) {
let index = -1;
const length = this.length;
while (++index < length) {
callback(this[index], index);
}
return this;
};
调用示例:
let arr = [1, 2, 5, 8];
arr.myforEach((value, index) => {
console.log(value, '-', index);
});
结果:

2. forEach 是无法通过任何方法跳出循环的,如果你把 try...catch... 算作方法,那另当别论。不过可以自己写一个 forEach 来实现这个功能;
Array.prototype.myforEach = function (callback) {
let index = -1;
const length = this.length;
while (++index < length) {
const res = callback(this[index], index);
// 这样可通过 return null 或者 false 跳出自己写的 forEach 循环了
if (typeof res !== "undefined" && (res == null || res == false)) {
break;
}
}
return this;
};

浙公网安备 33010602011771号