javascript - 缩短 JS if 或语句

标签 javascript

<分区>

在 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

您还可以将对象用作某种 HashMap :

//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')

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

关于javascript - 缩短 JS if 或语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5032461/

相关文章:

javascript - 如何删除表格并用 DIV 替换它们?

javascript - 我的应用程序读取 txt 文件,即使它们被删除

javascript - 如何捕获元素上数据属性的变化?

javascript - 在 mongoDB 中创建一个 firebase 样式的权限层次结构

javascript - 如何在 JavaScript 中部分应用成员函数?

javascript - Ruby/Sinatra 的 JSON 数据库模块? Ruby/Sinatra 的 JS lowDB 替代品?

javascript - Jquery 到原型(prototype)

javascript - SVG getIntersectionList 返回 null

javascript - Sum of Pairs : Codewars 优化解

javascript - 当写入文件代码被注释时,附加生成器中的构建失败