[1,2,3].forEach(function(el) {
if(el === 1) break;
});
Run Code Online (Sandbox Code Playgroud)
如何forEach在JavaScript中使用新方法执行此操作?我试过了return;,return false;而且break.break崩溃,return除了继续迭代之外什么都不做.
我正在玩nodejs和mongoose - 尝试在深层注释中找到特定注释,并使用递归函数和foreach进行嵌套.有没有办法阻止nodejs forEach?据我所知,每个forEach迭代都是一个函数而且我不能只做"休息",只能"返回",但这不会阻止foreach.
function recurs(comment){
comment.comments.forEach(function(elem){
recurs(elem);
//if(...) break;
});
}
Run Code Online (Sandbox Code Playgroud) 我只是创建一个函数来检查我的对象数组中的某个值,但由于某种原因它会一直返回undefined.这是为什么?
演示:http://jsfiddle.net/cNYwz/1/
var data = [{
"Key": "1111-1111-1111",
"Email": "test@test.com"
}, {
"Key": "2222-2222-2222",
"Email": "test@boo.com"
}];
function getByKey(key) {
data.forEach(function (i, val) {
if (data[val].Key === key) {
return data[val].Key;
} else {
return "Couldn't find";
}
});
}
var asd = getByKey('1111-1111-1111');
console.log(asd);
Run Code Online (Sandbox Code Playgroud)