无论如何在Javascript中缩短这样的东西:if (x == 1 || x == 2 || x == 3 || x == 4)像if这样的东西(x == (1 || 2 || 3 || 4))?
您可以使用Array.indexOf
[1,2,3,4].indexOf(x) !== -1
Run Code Online (Sandbox Code Playgroud)
您还可以将对象用作某种哈希映射:
//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')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在大多数情况下,您应该使用"==="严格相等运算符而不是==运算符.使用"=="进行比较可能会进行大量复杂的类型强制,有时您会得到令人惊讶的结果.
| 归档时间: |
|
| 查看次数: |
5418 次 |
| 最近记录: |