我正在使用Node.js和Mongoose -试图在深层注释嵌套中找到特定的注释,其中带有递归函数和forEach。有没有办法停止Node.js forEach?正如我所理解的,forEach迭代都是一个函数,我不能只做break,只做return,但这不会停止forEach。
function recurs(comment) {
comment.comments.forEach(function(elem) {
recurs(elem);
//if(...) break;
});
}
无法从Array#forEach中退出。(您可以在链接页面上查看在Firefox中实现它的源代码,以确认这一点。)
相反,你应该使用一个正常的for循环:
function recurs(comment) {
for (var i = 0; i < comment.comments.length; ++i) {
var subComment = comment.comments[i];
recurs(subComment);
if (...) {
break;
}
}
}
(或者,如果你想更聪明一点,comment.comments[i]总是一个对象:)
function recurs(comment) {
for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
recurs(subComment);
if (...) {
break;
}
}
}
我猜你想用array。prototype。find
Find在数组中找到特定值时将自行中断。
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
数组中。forEach不能被打破,使用try…catch或hack方法,如Array。每个或数组。有些只会让你的代码更难理解。这个问题只有两种解决方案:
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. Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. While this works for iterable objects (e.g. Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries method. 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. For Arrays, you won't need all this but compatibility remains a problem:
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)很多人会同意第一种选择和第二种选择都不是好的候选人。在选项2成为新的标准之前,大多数流行的库(如AngularJS和jQuery)都提供了自己的循环方法,这些方法比JavaScript中的任何可用方法都要优越。对于那些还没有使用这些大型库并且正在寻找轻量级选项的人来说,可以使用像这样的解决方案,并且几乎与ECMA6相同,同时保持与旧浏览器的兼容性。