Multiple conditions in an if clause

后端 未结 9 1047
醉梦人生
醉梦人生 2021-02-02 06:44

If I have an if statement that needs to meet these requirements:

if(cave > 0 && training > 0 && mobility > 0 && sleep > 0)
         


        
9条回答
  •  攒了一身酷
    2021-02-02 07:26

    As others have suggested, you can use .every if you don't mind using ES6 or polyfills:

    var hasAllStats = [cave, training, mobility, sleep]
      .every(function(stat) { return stat > 0; });
    
    if (hasAllStats) { }
    

    Alternatively, you can use .some to get the inverse (Also requires ES6 or polyfill):

    var isMissingStats = [cave, training, mobility, sleep]
      .some(function(stat) { return stat <= 0; });
    
    if (!isMissingStats) { }
    

    If you don't want to use ES6, you can use reduce:

    var hasAllStats = [cave, training, mobility, sleep]
      .reduce(function(hasAllStats, stat) {
        return hasAllStats && stat > 0;
      }, true);
    
    if (hasAllStats) { }
    

提交回复
热议问题