short hand for chaining logical operators in javascript?

后端 未结 7 1468
眼角桃花
眼角桃花 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:45

    Well, you could use a switch statement...

    switch (value) {
      case 1    : // blah
                  break;
      case 16   : // blah
                  break;
      case -500 : // blah
                  break;
      case 42.42: // blah
                  break;
      case "something" : // blah
                         break;
    }
    

    If you're using JavaScript 1.6 or greater, you can use the indexOf notation on an array:

    if ([1, 16, -500, 42.42, "something"].indexOf(value) !== -1) {
       // blah
    }
    

    And for the ultimate in hackiness, you can coerce the values to strings (this works for all browsers):

    if ("1,16,-500,42.42,something".indexOf(value) !== -1) {
       // blah
    }
    

提交回复
热议问题