我在玩 JSconsole 时发现了一些奇怪的东西。 "0"
的值为 false
"0" == false
=> true
false
的值在三元中使用时返回第二个值
false ? 71 : 16
=> 16
但是当在三进制中使用时等于 false
的值 "0"
返回第一个值。
"0" ? 8 : 10
=> 8
但是,如果您使用 0
作为值,它会返回第二个值
0 ? 4 : 5
=> 5
0 == "0"
=> true
恐怕这对我来说没有意义。
最佳答案
非空字符串在条件语句、条件表达式和条件构造中被视为真值。
但是当您使用 ==
将字符串与数字进行比较时,会发生一些转换。
When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
并且==
没有相等的传递性:
你不能说 if a == b, b == c, then a == c
。
一个例子是:
"0" == false // true
false == "\n" //true
并猜测 "0"== "\n"
的结果?是的,结果是 false
。
关于javascript - 为什么将 "0"与三元运算符一起使用会返回第一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670964/