Multiple conditions in an if clause

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

    You could use an array with .every. This is less DRY, but more verbose:

    var isGreaterThanZero = function(val) {
        return val > 0;
    };
    if([cave, training, mobility, sleep].every(isGreaterThanZero)) {
        // Do Something
    }
    

    The reason I like this is that by using an array, it becomes apparent that you're repeating logic for every variable. Naming the callback in an obvious manner helps future readers understand exactly what that check will achieve. And finally, this gives scope for not just numbers, but any check of any type in the future - with any complexity hidden away from the if statement itself.

提交回复
热议问题