缩短JS if或statement [英] Shorten JS if or statement
本文介绍了缩短JS if或statement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
反正可以用Javascript来简化如下代码: if(x == 1 || x == 2 || x == 3 || x == 4)
到if(x ==(1 || 2 || 3 || 4))
吗?
Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4)
to something like if (x == (1 || 2 || 3 || 4))
?
推荐答案
您可以使用 Array.indexOf
[1,2,3,4].indexOf(x) !== -1
您还可以将对象用作某种哈希图:
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
顺便说一句,在大多数情况下,您应该使用"==="严格相等运算符,而不是 ==
运算符.使用"=="进行比较可能会产生很多复杂的类型强制,有时您会得到令人惊讶的结果.
By the way, in most cases you should usi the "===" strict equality operator instead of the ==
operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.
这篇关于缩短JS if或statement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文