缩短JS if或statement

Joh*_*ohn 9 javascript

无论如何在Javascript中缩短这样的东西:if (x == 1 || x == 2 || x == 3 || x == 4)像if这样的东西(x == (1 || 2 || 3 || 4))

hug*_*omg 6

您可以使用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)

顺便说一句,在大多数情况下,您应该使用"==="严格相等运算符而不是==运算符.使用"=="进行比较可能会进行大量复杂的类型强制,有时您会得到令人惊讶的结果.

  • 好吧*有时*"=="很有用,但你可能正确"==="应该是JavaScript程序员自动输入的内容:-) (2认同)