我将向您展示我的应用程序的一小部分,我想知道哪种方法是放置我正在处理的条件的正确方法。如果我将向您展示的两种方式都是正确的,我希望您能告诉我后果/逆境
if ((some.thing === '' || 0) || (some.how === '' || 0)) {
//something is going on here
}
到目前为止我就是这样,有什么不好的地方吗?
或者应该这样更好:
if ((some.thing === '' || some.thing === 0) || (some.how === '' || some.how === 0)) {
//something is going on here
}
那么你有什么建议呢?最后结果一样吗?
编辑
添加另一种方式:
if (some.thing === '' || some.thing === 0 || some.how === '' || some.how === 0) {
//something is going on here
}
最佳答案
||
运算符优先于比较运算符。
所以 some.thing === '' || 0
与 (some.thing === '') || 相同(0)
。它:
- 如果
some.thing === ''
为false
或 ,则计算结果为 - 如果
some.thing === ''
为true
,则计算结果为true
。
0
看看这个例子(在 JavaScript 控制台中运行):
> some = { thing: 0 }
Object { thing: 0 }
> some.thing === ''
false
> some.thing === '' || 0 // this is like false || 0
0
> some = { thing: '' }
Object { thing: "" }
> some.thing === ''
true
> some.thing === '' || 0 // this is like true || 0
true
喜欢你写的最后一个表达式。
编辑:实际上 ''
和 0
都是 falsy在 JavaScript 中,所以你可以简单地将完整的表达式写成:
if (!some.thing || !some.how) {
//something is going on here
}
关于javascript - 通过特殊条件语句弄清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30903994/