javascript中链接逻辑运算符的简写?
有没有更好的方法在 JavaScript 中编写以下条件?
if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == 'something' ) {
// blah blah blah
}
我讨厌将所有这些逻辑“或”串在一起。我想知道是否有某种简写。
谢谢!
Is there a better way to write the following conditional in javascript?
if ( value == 1 || value == 16 || value == -500 || value == 42.42 || value == 'something' ) {
// blah blah blah
}
I hate having all of those logical ORs strung together. I'm wondering if there is some kind of shorthand.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
更新:
评论中建议的实用函数示例:
所以你可以写:
Upd:
Utility function sample as proposed in comments:
So you can write:
您可以扩展数组对象:
然后,如果您将所有这些值存储在数组中,您可以执行类似 MyValues.contains(value) 的操作
You could extend the array object:
Then if you store all those values in an array you could do something like MyValues.contains(value)
不,这是简写。
作为替代方案,您可以执行
switch
如果您需要很多可能的值,这更容易管理,但实际上您的版本无论如何都较短:)
nope, that is the shorthand.
as an alternative, you can do a
switch
which is easier to manage if you need a lot of possible values, but actually your version is shorter anyway :)
开关是一个可以接受的选择。您还可以使用地图,具体取决于问题的复杂性(假设您的问题比示例中输入的复杂程度多)。
当然,accept 可以从数组中以编程方式生成。实际上取决于您计划使用此模式的程度。 :/
switch is an acceptable choice. You can also use a map, depending on the complexity of the problem (assuming you have more than you put in your example).
accept could be generated progamatically from an array of course. Depends really on how much you plan on using this pattern. :/
好吧,你可以使用 switch 语句...
如果你使用 JavaScript 1.6 或更高版本,你可以在数组上使用 indexOf 表示法:
并且为了实现最终的 hackiness,你可以将值强制转换为字符串(这适用于所有浏览器):
Well, you could use a switch statement...
If you're using JavaScript 1.6 or greater, you can use the indexOf notation on an array:
And for the ultimate in hackiness, you can coerce the values to strings (this works for all browsers):
努力尝试另一种方法......
不需要扩展数组原型或任何东西,只需使用快速正则表达式来测试值!
In an effort to make yet another way of doing it...
No need to extend array prototypes or anything, just use a quick regexp to test the value!