是否有更好的方法来处理检查多个值。当我有3个以上的选择时,它就开始变得很忙了。
if (myval=='something' || myval=='other' || myval=='third') {
}
PHP有一个叫做in_array()
的函数,它的用法如下:
in_array($myval, array('something', 'other', 'third'))
在js或jquery中有类似的东西吗?
Jquery.inArray()
除了$.inArray
,您还可以使用Object表示法:
if (myval in {'something':1, 'other':1, 'third':1}) {
...
或
if (({'something':1, 'other':1, 'third':1}).hasOwnProperty(myval)) {
....
(注意,如果客户端修改了Object.prototype
,第一个代码将不起作用)
可以使用某种哈希映射来避免遍历数组:
var values = {
'something': true,
'other': true,
'third': true
};
if(values[myVal]) {
}
也可以不使用jQuery;)
取自10+ JAVASCRIPT速记编码技术的简洁解决方案:
手写
if (myval === 'something' || myval === 'other' || myval === 'third') {
alert('hey-O');
}
速记if(['something', 'other', 'third'].indexOf(myvar) !== -1) alert('hey-O');