有没有更好的方法在javascript中编写以下条件?
if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == 'something' ) {
// blah blah blah
}
我讨厌将所有这些逻辑 OR 串在一起。我想知道是否有某种速记。
谢谢!
有没有更好的方法在javascript中编写以下条件?
if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == 'something' ) {
// blah blah blah
}
我讨厌将所有这些逻辑 OR 串在一起。我想知道是否有某种速记。
谢谢!
var a = [1, 16, -500, 42.42, 'something'];
var value = 42;
if (a.indexOf(value) > -1){
// blah blah blah
}
更新: 评论中提出的实用函数示例:
Object.prototype.in = function(){
for(var i = 0; i < arguments.length; i++){
if (this == arguments[i]) return true;
}
return false;
}
所以你可以写:
if (value.in(1, 16, -500, 42.42, 'something')){
// blah blah blah
}
您可以扩展数组对象:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
然后,如果您将所有这些值存储在一个数组中,您可以执行类似 MyValues.contains(value) 的操作
不,这是简写。
作为替代方案,您可以执行switch
switch (value) {
case 1 :
case 16 :
case -500 :
....
}
如果您需要很多可能的值,这更容易管理,但实际上您的版本更短:)
var value= -55;
switch(value){
case 1: case 16: case -55: case 42.5: case 'something':
alert(value); break;
}
switch 是一个可以接受的选择。您还可以使用地图,具体取决于问题的复杂性(假设您拥有的比示例中的多)。
var accept = { 1: true, 16: true, '-500': true, 42.42: true, something: true };
if (accept[value]) {
// blah blah blah
}
accept 当然可以从数组中以编程方式生成。真正取决于您计划使用这种模式的程度。:/
好吧,您可以使用 switch 语句...
switch (value) {
case 1 : // blah
break;
case 16 : // blah
break;
case -500 : // blah
break;
case 42.42: // blah
break;
case "something" : // blah
break;
}
如果您使用的是 JavaScript 1.6 或更高版本,则可以在数组上使用 indexOf 表示法:
if ([1, 16, -500, 42.42, "something"].indexOf(value) !== -1) {
// blah
}
对于最终的hackiness,您可以将值强制转换为字符串(这适用于所有浏览器):
if ("1,16,-500,42.42,something".indexOf(value) !== -1) {
// blah
}
在努力做出另一种方式来做到这一点......
if (/^(1|16|-500|42.42|something)$/.test(value)) {
// blah blah blah
}
无需扩展数组原型或任何东西,只需使用快速正则表达式来测试值!