为什么“真实” == true在JavaScript中显示false? [英] Why does "true" == true show false in JavaScript?

查看:203
本文介绍了为什么“真实” == true在JavaScript中显示false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDC描述 == 运算符如下

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:


  1. 它们是否属于同一类型?

  2. 操作数是数字还是布尔值?

  3. 我们可以将两者都转换为数字吗? isNaN(Number(true))// true

  4. 是否为操作数a串?

  5. 我们可以将其他操作数转换为字符串吗? 字符串(true)===true// true

  1. Are they of the same type? No
  2. Is either operand a number or boolean? Yes
  3. Can we convert both to a number? No (isNaN(Number("true")) // true)
  4. Is either operand a string? Yes
  5. Can we convert the other operand to a string? Yes (String(true) === "true" // true)

我最终得到了字符串truetrue ,它应该评估为 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆