为什么将“0”与三元运算符 return 一起使用是第一个值?

Why does using "0" with the ternary operator return the first value?

我在玩 JSconsole,发现了一些奇怪的东西。 "0" 的值为 false

"0" == false
=> true

三进制时false的值returns第二个值

false ? 71 : 16
=> 16

然而,值 "0" 等于 false 用于三元 returns 第一个值。

"0" ? 8 : 10
=> 8

但是,如果您使用 0 作为值,它 returns 第二个值

0 ? 4 : 5
=> 5

0 == "0"
=> true

恐怕这对我来说没有意义。

"0" 是长度 >0 字符串 ,即 true。尝试

0 ? 8 : 10

看看。它将 return 10.

== 进行 类型转换 ,因此当您进行

"0" == false

它 returns true。当你这样做时

0 == "0" //true

它也 return 正确,因为类型转换再次发生。尽管一个是 number 而另一个是 string,但它 return 是正确的。但是如果你使用 === 没有 类型转换完成并且 0 === "0" 将 return false.

== & === 的一个很好的解释 here.

来自docs:

The equality operator(==) converts the operands if they are not of the same type, then applies strict comparison.

The identity operator(===) returns true if the operands are strictly equal with no type conversion.

恐怕这就是为什么您应该使用 === 的示例 - 普通的旧 == 执行类型转换。尝试

"0"===false

非空字符串在条件语句、条件表达式和条件构造中被视为真值。

但是当你用 == 比较字符串和数字时,会发生一些转换。

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 导致成吨的 WTF。

在 YouTube 上查看 "Javascript WTF"...

本质上,您是在请求 从字符串到布尔值的转换

这定义为"string is not empty"。

而您假设 javascript 如果字符串恰好包含数字,则执行字符串 -> 整数 -> 布尔值。

明智。但是这些自动转换会导致编程错误,这就是为什么我更喜欢类型安全语言(具有编译时类型检查)用于大型项目。

为了好玩,试试这些:

("0" * 1) ? 71 : 16
("0" + false) ? 71 : 16