有没有更快的OR运算符编写方法? [英] Is there a faster way of writing OR operator?

查看:51
本文介绍了有没有更快的OR运算符编写方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更快的书写方式?

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!')
};

我在想类似的东西:

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

推荐答案

您可以使用

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!')
};

以上功能将在IE9 +中运行,对于较旧的浏览器,您可以使用 jQuery.inArray(值,数组)

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!')
};

这篇关于有没有更快的OR运算符编写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆