javascript - 为什么将 "0"与三元运算符一起使用会返回第一个值?

标签 javascript types ternary-operator

我在玩 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/

相关文章:

types - 如何创建转换器?

Ruby 多行三元表达式?

javascript - 纯 HTML 小部件安全吗?

javascript - Google Plus 使用 Javascript 发帖?

c# - 如何从字符串表示中获取泛型类型?

mysql - Facebook user_id : big_int, 整数还是字符串?

python - 条件表达式/三元运算符

c# - 检查一行 C# 中的数组元素是否不为空

javascript - 将第三方视频集成到 Web 应用程序中

Google 表格中的 JavaScript 函数