为什么“真实” == true在JavaScript中显示false? [英] Why does "true" == true show false in JavaScript?
问题描述
MDC describes the ==
operator as follows:
如果两个操作数的类型不同,则JavaScript转换操作数然后应用严格比较。如果操作数是数字或布尔值,操作数将尽可能转换为数字;否则,如果任一操作数是一个字符串,如果可能,另一个操作数将转换为字符串。
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
考虑到这一点,我会评估true== true
如下:
With this in mind, I would evaluate "true" == true
as follows:
- 它们是否属于同一类型? 否
- 操作数是数字还是布尔值? 是
- 我们可以将两者都转换为数字吗? 否(
isNaN(Number(true))// true
) - 是否为操作数a串? 是
- 我们可以将其他操作数转换为字符串吗? 是(
字符串(true)===true// true
)
- Are they of the same type? No
- Is either operand a number or boolean? Yes
- Can we convert both to a number? No (
isNaN(Number("true")) // true
) - Is either operand a string? Yes
- Can we convert the other operand to a string? Yes (
String(true) === "true" // true
)
我最终得到了字符串true
和true
,它应该评估为 true
,但JavaScript显示为false。
I've ended up with the strings "true"
and "true"
, which should evaluate to true
, but JavaScript shows false.
我错过了什么?
推荐答案
因为true
转换为 NaN
,而 true
转换为 1
。所以他们不同。
Because "true"
is converted to NaN
, while true
is converted to 1
. So they differ.
就像你报道的那样,两者都被转换为数字,因为至少 true
可以(见Erik Reppen的评论),然后比较。
Like you reported, both are converted to numbers, because at least true
can be (see Erik Reppen's comment), and then compared.
这篇关于为什么“真实” == true在JavaScript中显示false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!