short hand for chaining logical operators in javascript?

后端 未结 7 1467
眼角桃花
眼角桃花 2021-01-12 03:13

Is there a better way to write the following conditional in javascript?

if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == \'somet         


        
7条回答
  •  梦谈多话
    2021-01-12 03:52

    var a = [1, 16, -500, 42.42, 'something'];
    var value = 42;
    if (a.indexOf(value) > -1){
    // blah blah blah
    }
    

    Upd: Utility function sample as proposed in comments:

    Object.prototype.in = function(){
      for(var i = 0; i < arguments.length; i++){
        if (this == arguments[i]) return true;
      }
      return false;
    }
    

    So you can write:

    if (value.in(1, 16, -500, 42.42, 'something')){
    // blah blah blah
    }
    

提交回复
热议问题