short hand for chaining logical operators in javascript?

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

    You could extend the array object:

    Array.prototype.contains = function(obj) {
      var i = this.length;
      while (i--) {
        if (this[i] == obj) {
          return true;
        }
      }
      return false;
    }
    

    Then if you store all those values in an array you could do something like MyValues.contains(value)

    0 讨论(0)
  • 2021-01-12 03:40
    var value= -55;
    switch(value){
        case 1: case 16: case -55: case 42.5: case 'something': 
            alert(value); break;        
    
    }
    
    0 讨论(0)
  • 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. :/

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-01-12 03:50

    In an effort to make yet another way of doing it...

    if (/^(1|16|-500|42.42|something)$/.test(value)) {
      // blah blah blah
    }
    

    No need to extend array prototypes or anything, just use a quick regexp to test the value!

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题