Where does the return value go for a forEach callback?
This question already has an answer here:
You can break out of the loop, but the return value is unused.
Since forEach
doesn't return anything itself, it wouldn't make much sense to collect return values from the callback.
To break out, you need to throw
during the callback:
var newForEach = function (obj, func, con) {
if (Pub.isType("Function", func)) {
Object.keys(obj).forEach(function (key) {
if (func.call(con, obj[key], key, obj)) {
throw new Error('something terrible happened!');
}
});
}
};
However , that looks like exceptions as flow control, which is a Very Bad Thing. If that is what you're doing, there are probably other array methods that will be more helpful: perhaps every
or filter
.
The return value goes nowhere.
If you want to break out a forEach
, then use some
instead. It breaks when you return a truthy value.
Taken from the MDN documentation on forEach
:
There is no way to stop or break a forEach()
loop other than by throwing an exception. If you need such behavior, 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. If available, the new methods find()
or findIndex()
can be used for early termination upon true predicates as well.
上一篇: 为什么这段代码不会返回false?
下一篇: forEach回调的返回值在哪里?