function(callback) {
console.log(1, '*****');
var array = ['hello'];
array.forEach(element) {
if (element === 'hello') {
console.log(2, '*****');
return callback(true); // doesn't end or return here. not sure why?
}
}
console.log(3, '*****');
return callback(false);
}
//current output
1 '*****'
2 '*****'
3 '*****'
//Desired output
1 '*****'
2 '*****'
为什么即使满足了if条件,控制流程还是一路结束?为什么它不立即返回回调?
最佳答案
return
语句实际上不会返回到 function(callback)
,而是将值返回到 forEach
函数。
From MDN docs: Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.
关于javascript - forEach 内部和 forEach 之后的条件回调,但似乎没有按预期返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33824034/