为什么在JavaScript中用double等于“==”的真正匹配“true”? [英] Why does not the true match 'true' with double equals sign '==' in JavaScript?

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

问题描述

这小部分代码花了很长时间才被注意到。

This small portion of code took a long time to be noticed.

我想如果我做下面的事情,就会很好

I thought if I do the following, it would be fine

if('true' == true) {
    alert("Does not happen");
}

但它不通过if条件。

But it does not pass the if condition.

我认为double等于 == 匹配的值不是类型匹配的类型是作业 ===

I thought the double equals == matches the value not the type as matching the type is the job of ===.

现在我的问题是为什么 true typecast to 'true'或为什么要检查这些操作数的类型?

Now my questions are why wasn'the true typecast to 'true' or why is it checking for the type of these operands?

推荐答案

'true' == true

这是这里发生的(根据规则):

This is what happens here (according to the rules):

- 将布尔值转换为数字(规则7):

-- convert boolean to a number (rule 7):

'true' == 1

- 将'true'转换为数字(规则5):

-- convert 'true' to Number (rule 5):

Number('true') == 1

- 数字('true') NaN

NaN == 1

- return false(rule 1.ci)

-- return false (rule 1.c.i)

== 确实令人困惑,感知一旦你理解规则:

== is indeed confusing, but it makes some sense once you understand the rules:


  • 垃圾等于垃圾(undefined == null)

  • 没有布尔值(以数字形式比较)

  • 如果其中一个零件是数字,请比较数字

  • 一个字符串,比较为字符串

  • 否则,a和b必须是相同的东西。

  • garbage is equal to garbage (undefined == null)
  • no booleans (they're compared as numbers)
  • if one of the parts is a number, compare numeric
  • if one of the parts is a string, compare as strings
  • otherwise, a and b must be the same thing.

这篇关于为什么在JavaScript中用double等于“==”的真正匹配“true”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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