为什么使用“ 0”?用三元运算符返回第一个值? [英] Why does using "0" with the ternary operator return the first value?
问题描述
我在玩JSconsole时发现了一些奇怪的东西。 0
的值为假
I was playing around with JSconsole and found something strange. The value of "0"
is false
"0" == false
=> true
false
的值用于三元返回第二个值
The value of false
when used in ternary returns the second value
false ? 71 : 16
=> 16
但是值 0
在三元数中使用时等于 false
返回第一个值。
However the value "0"
which equals false
when used in ternary returns the first value.
"0" ? 8 : 10
=> 8
但是,如果您使用 0
作为该值,则返回第二个值
However, if you use 0
as the value, it returns the second value
0 ? 4 : 5
=> 5
0 == "0"
=> true
我恐怕这对我没有意义。
I'm afraid this doesn't make sense to me.
推荐答案
0&;
是字符串长度为> 0
的em>,其值为 true
。尝试
"0"
is a string of length>0
which is true
. Try
0 ? 8 : 10
然后看。它将返回 10
。
==
进行类型转换,因此当您这样做时
==
does type conversion and hence when you do
"0" == false
返回 true
。
0 == "0" //true
当再次进行类型转换时,它也返回true。即使一个是数字
,而另一个是字符串
,它也会返回true。但是,如果使用 ===
,则完成否类型转换,并且 0 === 0
将返回 false
。
It also returns true as again type conversion is taking place. Even though one is a number
and the other one is a string
it returns true. But if you use ===
, no type conversion is done and 0 === "0"
will return false
.
对 == $ c $的一个很好的解释c>&在 此处给出
===
/ strong> 。
A nice explanation of ==
& ===
is given here.
来自 文档 :
等于运算符(
==
)如果操作数的类型不同,则将其转换,然后应用严格比较。
The equality operator(
==
) converts the operands if they are not of the same type, then applies strict comparison.
身份运算符( ===
)如果操作数严格相等且没有类型转换,则返回 true 。
The identity operator(===
) returns true if the operands are strictly equal with no type conversion.
这篇关于为什么使用“ 0”?用三元运算符返回第一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!