[英]javascript if else shorthand and strings
var x = 'x' x-'m'||console.log('True 1') // logs True, should be false var x = '2' x-2||console.log('True 2') // logs True var x = '3' x-2||console.log('True 3') // logs False
Why does this if else shorthand always return true when using a string?为什么 if else 速记在使用字符串时总是返回 true ? How can it be fixed?如何修复?
If the expression before the ||
如果||
之前的表达式returns a falsy
expression, then the console.log()
is executed.返回一个falsy
表达式,然后执行console.log()
。 This happens for the first expression 'x' - 'm'
which produces NaN
(which is falsy):这发生在第一个表达式'x' - 'm'
产生NaN
(这是假的):
console.log('x' - 'm')
and for the second expression '2' - 2
which returns 0
(which is falsy):对于第二个表达式'2' - 2
返回0
(这是假的):
console.log('2' - 2)
Your console.log()
does not get executed for the third expression '3' - 2
because that returns 1
(which is truthy):您的console.log()
不会为第三个表达式'3' - 2
执行,因为它返回1
(这是真的):
console.log('3' - 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.