Return value for function instead of inner function in Array.forEach

This question already has an answer here:

  • How to short circuit Array.forEach like calling break? 24 answers

  • 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

    上一篇: 在Javascript中迭代JSON字符串的最快方法

    下一篇: 返回Array.forEach中函数的值而不是内部函数的值