Javascript compare 3 values

后端 未结 7 2412
执笔经年
执笔经年 2020-11-29 11:04

I have 3 values that I want to compare f, g and h. I have some code to check that they all equal each other and that none of them are null. I\'ve had a look online but could

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 11:39

    You could shorten that to

    if(g === h && g === f && g !== null)
    {
    //do something
    }
    

    For an actual way to compare multiple values (regardless of their number)
    (inspired by/ simplified @Rohan Prabhu answer)

    function areEqual(){
       var len = arguments.length;
       for (var i = 1; i< len; i++){
          if (arguments[i] === null || arguments[i] !== arguments[i-1])
             return false;
       }
       return true;
    }
    

    and call this with

    if( areEqual(a,b,c,d,e,f,g,h) )
    {
    //do something
    }
    

提交回复
热议问题