MDC describes the ==
operator as follows :
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
:
- 它们属于同一类型吗? 否
- 操作数是数字还是 bool 值? 是
- 我们可以将两者都转换为数字吗? 否 (
isNaN(Number("true"))//true
) - 操作数是字符串吗? 是
- 我们可以将另一个操作数转换为字符串吗? 是 (
String(true) === "true"//true
)
我以字符串 "true"
和 "true"
结束,它们的计算结果应该为 true
,但 JavaScript 显示为 false .
我错过了什么?
最佳答案
因为"true"
被转换为NaN
,而true
被转换为1
。所以他们不同。
正如您报告的那样,两者都被转换为数字,因为至少 true
可以(参见 Erik Reppen 的评论),然后进行比较。
关于javascript - 为什么 "true"== true 在 JavaScript 中显示为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363659/