short hand for chaining logical operators in javascript?

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

    switch is an acceptable choice. You can also use a map, depending on the complexity of the problem (assuming you have more than you put in your example).

    var accept = { 1: true, 16: true, '-500': true, 42.42: true, something: true };
    if (accept[value]) {
      // blah blah blah
    }
    

    accept could be generated progamatically from an array of course. Depends really on how much you plan on using this pattern. :/

提交回复
热议问题