Multiple conditions in an if clause

后端 未结 9 1049
醉梦人生
醉梦人生 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:10

    Filter it with lodash:

    var data = [cave, training, mobility, sleep];
    var result = _.filter(data, function (datum) { return datum > 0; }).length === data.length;
    
    console.log(result);
    

    It iterates over array elements and returns new array composed of those elements that meet given requirement of being > 0 - if result array is different size than given one it means one or more of it's elements were not > 0.

    I wrote it specifically to check every array value (even if not necessary as first > 0 could give same result) to not stop on first positive as you stated you want to check all of them.

    PS You can reverse it to check for <= 0 and check for .length === 0 instaed to be faster.

提交回复
热议问题