javascript - 为什么 "true"== true 在 JavaScript 中显示为 false?

标签 javascript string equals

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:

  1. 它们属于同一类型吗?
  2. 操作数是数字还是 bool 值?
  3. 我们可以将两者都转换为数字吗? (isNaN(Number("true"))//true)
  4. 操作数是字符串吗?
  5. 我们可以将另一个操作数转换为字符串吗? (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/

相关文章:

c# - Linq-EF 中的自定义扩展方法等同于 SQL "IN"子句

javascript - 使用 Google App 脚本替换 Google Sheet 中的文本而不重新格式化值

java - 'equals()' 返回 false,但在 map 中找到了对象

javascript - 字母值是否输入到 ng-model 保存的数字输入中?

javascript - SyntaxError : Unexpected token < in JSON at position 0 at Object. 解析( native )(AngularJS)

javascript - Google map API v3 - 是否可以添加非特定位置,例如大陆或国家?

使用 sprintf() 将文本复制到字符数组中 - C/Atmel studio 7

javascript - Jquery 表单 : using the memento pattern to build a dirty form notification system - exisitng patterns?

java - 按键集比较 map

java - 如何在 Java 中使用 Math.random() 生成等概率随机数