本文翻译自:how to stop Javascript forEach? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- Short circuit Array.forEach like calling break 28 answers 短路Array.forEach就像调用break 28的答案
i'm playing with nodejs and mongoose — trying to find specific comment in deep comments nesting with recursive func and foreach within. 我正在玩nodejs和mongoose - 尝试在深层注释中找到特定注释,并使用递归函数和foreach进行嵌套。 Is there a way to stop nodejs forEach? 有没有办法阻止nodejs forEach? As i understand every forEach iteration is a function and and i can't just do "break",only "return" but this won't stop foreach. 据我所知,每个forEach迭代都是一个函数而且我不能只做“休息”,只能“返回”,但这不会阻止foreach。
function recurs(comment){
comment.comments.forEach(function(elem){
recurs(elem);
//if(...) break;
});
}
#1楼
参考:https://stackoom.com/question/QGhw/如何停止Javascript-forEach-重复
#2楼
在某些情况下, Array.some
可能会满足要求。
#3楼
Wy not use plain return? Wy不使用普通退货?
function recurs(comment){
comment.comments.forEach(function(elem){
recurs(elem);
if(...) return;
});
it will return from 'recurs' function. 它将从'recurs'函数返回。 I use it like this. 我这样用它。 Althougth this will not break from forEach but from whole function, in this simple example it might work 虽然这不会从forEach中断,但是从整个函数中解脱出来,在这个简单的例子中它可能会起作用
#4楼
var f = "how to stop Javascript forEach?".split(' ');
f.forEach(function (a,b){
console.info(b+1);
if (a == 'stop') {
console.warn("\tposition: \'stop\'["+(b+1)+"] \r\n\tall length: " + (f.length));
f.length = 0; //<--!!!
}
});
#5楼
You can break from a forEach loop if you overwrite the Array method: 如果覆盖Array方法,则可以从forEach循环中断:
(function(){
window.broken = false;
Array.prototype.forEach = function(cb, thisArg) {
var newCb = new Function("with({_break: function(){window.broken = true;}}){("+cb.replace(/break/g, "_break()")+"(arguments[0], arguments[1], arguments[2]));}");
this.some(function(item, index, array){
newCb(item, index, array);
return window.broken;
}, thisArg);
window.broken = false;
}
}())
example: 例:
[1,2,3].forEach("function(x){\
if (x == 2) break;\
console.log(x)\
}")
Unfortunately with this solution you can't use normal break inside your callbacks, you must wrap invalid code in strings and native functions don't work directly (but you can work around that) 不幸的是,使用这个解决方案你不能在你的回调中使用正常的break,你必须在字符串中包含无效的代码,并且本机函数不能直接工作(但你可以解决这个问题)
Happy breaking! 快乐破!
#6楼
Array.forEach
cannot be broken and using try...catch
or hacky methods such as Array.every
or Array.some
will only make your code harder to understand. 无法破坏Array.forEach
并使用try...catch
或hacky方法(如Array.every
或Array.some
只会使您的代码更难理解。 There are only two solutions of this problem: 这个问题只有两个解决方案:
1) use a old for
loop: this will be the most compatible solution but can be very hard to read when used often in large blocks of code: 1)使用旧的for
循环:这将是最兼容的解决方案,但在大块代码中经常使用时很难读取:
var testArray = ['a', 'b', 'c'];
for (var key = 0; key < testArray.length; key++) {
var value = testArray[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
2) use the new ECMA6 (2015 specification) in cases where compatibility is not a problem. 2)在兼容性不成问题的情况下使用新的ECMA6(2015规范)。 Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. 请注意,即使在2016年,只有少数浏览器和IDE为此新规范提供了良好的支持。 While this works for iterable objects (eg Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries
method. 虽然这适用于可迭代对象(例如Arrays),但如果要在非可迭代对象上使用它,则需要使用Object.entries
方法。 This method is scarcely available as of June 18th 2016 and even Chrome requires a special flag to enable it: chrome://flags/#enable-javascript-harmony
. 自2016年6月18日起,这种方法几乎无法使用,甚至Chrome也需要一个特殊标志来启用它: chrome://flags/#enable-javascript-harmony
。 For Arrays, you won't need all this but compatibility remains a problem: 对于Arrays,您不需要所有这些,但兼容性仍然是一个问题:
var testArray = ['a', 'b', 'c'];
for (let [key, value] of testArray.entries()) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
3) A lot of people would agree that neither the first or second option are good candidates. 3)很多人都同意第一种或第二种选择都不是好的候选者。 Until option 2 becomes the new standard, most popular libraries such as AngularJS and jQuery offer their own loop methods which can be superior to anything available in JavaScript. 在选项2成为新标准之前,大多数流行的库(如AngularJS和jQuery)都提供了自己的循环方法,这些方法可以优于JavaScript中的任何可用方法。 Also for those who are not already using these big libraries and that are looking for lightweight options, solutions like this can be used and will almost be on par with ECMA6 while keeping compatibility with older browsers. 此外,对于尚未使用这些大型库并且正在寻找轻量级选项的用户,可以使用此类解决方案,并且几乎与ECMA6相同,同时保持与旧版浏览器的兼容性。