How to call outer function's return from inner function?

后端 未结 4 1008
抹茶落季
抹茶落季 2020-12-15 03:05

I have such code:

function allValid() {
    $(\'input\').each(function(index) {
        if(something) {
            return false; 
        }    
    });

            


        
相关标签:
4条回答
  • 2020-12-15 03:30

    Yeah, store it in a local variable.

    function allValid() {
      var allGood = true;
      $('input').each(function (index) {
        if (something) {
          allGood = false;
        }
      });
    
      return allGood;
    }
    
    0 讨论(0)
  • 2020-12-15 03:34

    You could also use Array.prototype.some which iterates until finding an element that matches the criteria.

    function allValid() {
        var inputs = $('input');
        if(inputs.toArray().some(function(input){
            if(something)
                return true;
        })) {
            return false;
        } else {
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 03:43

    You can also do this with filter:

    var anyInvalid = $('input').filter(function(index) {
                       if(inValidCheck)
                         return true;
                     }).length;
    

    This works because 0 is treated as false, but it actually gives you the number of invalid, which you could use this to display "You have 3 invalid entries" or something if you wanted.

    0 讨论(0)
  • 2020-12-15 03:51

    If you want to do this efficiently, I think this is the best way:

    function allValid() {
      elements = $('input')
      for (i = 0; i < elements.length; i++) { invalidityCheck(elements[i]) && return false; }
      return true;
    }
    

    Edit: Although a more JavaScript-y version would probably use exceptions:

    function allValid() {
      try
        $('input').each(function(index)) {
          if (something) { throw 'something happened!'; }
        });
      catch (e) {
        if (e == 'something happened!') {
          return false;
        } else {
          throw e;
        }
      }
      return true;
    }
    
    0 讨论(0)
提交回复
热议问题