在forEach中用return不会返回,函数会继续执行。
arr.forEach(callback[, thisArg]),callback会接收到三个参数:currentValue、index、array。
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.forEach(function (value, index, _ary) {
console.log(value);
return value === "CoffeeScript";
});
程序并不会中断执行。
JavaScript
Java
CoffeeScript
TypeScript
循环外使用try… catch,当需要中断时throw 一个异常,然后catch进行捕获。
try {
ary.forEach(function (el) {
console.log(el);
if (el === "CoffeeScript") throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
};
JavaScript
Java
CoffeeScript
重写forEach(也是借鉴第一种方法)
(function () {
if (typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
var oldForEach = Array.prototype.forEach;
if (oldForEach) {
Array.prototype.forEach = function () {
try {
oldForEach.apply(this, [].slice.call(arguments, 0));
}
catch (e) {
if (e !== StopIteration) {
throw e;
}
}
};
}
})();
ary.forEach(function (val) {
console.log(val);
if (val === "CoffeeScript")
throw StopIteration;
});
官方推荐方法(替换方法):用every和some替代forEach函数。every在碰到return false的时候,中止循环。some在碰到return true的时候,中止循环
使用 some 函数
ary.some(function (value, index, _ary) {
console.log(value);
return value === "CoffeeScript";
});
JavaScript
Java
CoffeeScript
使用 every 函数
ary.every(function (value, index, _ary) {
console.log(value);
return value === "CoffeeScript";
});
JavaScript
使用 for…of 函数
for (let el of ary) {
console.log(el);
if (el === "CoffeeScript") {
break;
}
}
JavaScript
Java
CoffeeScript
如何实现一个 forEach ?
其实本质上还是使用了 for 循环。使用 call,改变 callback。
Array.prototype.forEach = function (callback) {
console.log('this is my forEach')
if (this === undefined) {
throw new TypeError('this is null or not undefined')
}
if (typeof callback !== "function") {
throw new TypeError(callback + 'is not a function')
}
// this:当前调用的对象
const o = Object(this);
// len: 长度
const len = o.length >>> 0
for (let i = 0; i < len; i++) {
if (i in o) {
callback.call(null, o[i], i);
}
}
}