Return value for function instead of inner function in Array.forEach
This question already has an answer here:
Use Array#every
for checking the elements
function isValid(source, target) {
return arr.every(function (el) {
return el.value !== 3;
});
}
The same with Array#some
function isValid(source, target) {
return !arr.some(function (el) {
return el.value === 3;
});
}
You can't.
See the documentation from MDN:
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.
会很好地使用正常for in
,但与forEach
你可以这样做:
function isValid(source, target) {
var r = true;
arr.forEach(function (el) {
if (el.value === 3) {
r = false;
return false; // terminate loop
}
});
return r;
}
链接地址: http://www.djcxy.com/p/70064.html