Is there a faster way of writing OR operator?

前端 未结 6 1728
自闭症患者
自闭症患者 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: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) { ... }
    

提交回复
热议问题