Is there a faster way of writing OR operator?

前端 未结 6 1668
自闭症患者
自闭症患者 2021-01-13 08:31

Is there a faster way of writing this?

if ($(\'#id\').val()==7 || $(\'#id\').val()==8 || $(\'#id\').val()==9){
    console.log(\'value of #id is 7, 8, or 9!\         


        
相关标签:
6条回答
  • 2021-01-13 09:06

    You could also use $.inArray()

    if($.inArray(+$('#id').val(),[7,8,9])) > -1)
        console.log('value of #id is 7, 8, or 9!')
    };
    
    0 讨论(0)
  • 2021-01-13 09:14

    It's not really much simpler, unless the list of values is really long:

    if ([7, 8, 9].indexOf(parseInt($('#id').val(), 10)) != -1)
    
    0 讨论(0)
  • 2021-01-13 09:15

    You can use indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

    if ([7,8,9].indexOf(+$('#id').val()) > -1){
        console.log('value of #id is 7, 8, or 9!')
    };
    

    The above function will work in IE9+, for older browser's you can use either PolyFill or jQuery.inArray(value, array)

    if (jQuery.inArray(+$('#id').val(),[7,8,9]) > -1){
        console.log('value of #id is 7, 8, or 9!')
    };
    
    0 讨论(0)
  • 2021-01-13 09:18

    You could do a switch:

    switch($('#id').val()){
        case 7:
        case 8:
        case 9:
            console.log('value of #id is 7, 8, or 9!');
            break;
        default:
            console.log('value of #id is NOT 7, 8, or 9!')
    }
    
    0 讨论(0)
  • 2021-01-13 09:26

    The best thing you can do to speed up your code is to cache that DOM reference:

    var idval = +$('#id').val();
    if (idval === 7 || idval === 8 || idval === 9) { ...  }
    

    Of course if it's really those three values, then:

    if (idval >= 7 && idval <= 9) { ... }
    
    0 讨论(0)
  • 2021-01-13 09:27

    I just added this one to the jsperf: the in operator. The value in every key:value (e.g. 7:7) pair is irrelevant here.

    if ($('#id').val() in {7:7, 8:8, 9:9}) {
      console.log('value of #id is 7, 8, or 9!')
    };
    

    see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

    0 讨论(0)
提交回复
热议问题