Skip to content

== 和 ===的区别 #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Twlig opened this issue Mar 28, 2022 · 0 comments
Open

== 和 ===的区别 #78

Twlig opened this issue Mar 28, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Mar 28, 2022

js中各种类型转换为Boolean类型

数据类型 转换为true的值 转换为false的值
Boolean true false
String 任何非空字符串 空字符串
Number 任何非零数字值(包括无穷大) 0和null
Object 任何对象 null
Undefined   Undefined

注意

  • [],{}转换为Boolean也是true

  • Boolean(new Boolean(false))也是true

转换后是false的:

  • undefined

  • null

  • -0

  • +0

  • NaN

  • ‘’(空字符串)

使用 == 和 ===区别

  • == 如果不相等会进行隐式类型转换,会去调用变量的valueOf、toStirng方法。

  • === 则不会进行隐式类型转换

在转换操作数的类型时,相等和不相等操作符遵循如下规则。

  • 如果任一操作数是布尔值,则将其转换为数值再比较是否相等。false 转换为 0,true 转换为 1

    2 == true  //false2 == false //false
  • 如果一个操作数是字符串,另一个操作数是数值,则尝试将字符串转换为数值,再比较是否相等。

  • 如果一个操作数是对象,另一个操作数不是,则调用对象的 valueOf()方法取得其原始值,再根据前面的规则进行比较。

在进行比较时,这两个操作符会遵循如下规则。

  • null 和 undefined 相等。

  • null 和 undefined 不能转换为其他类型的值再进行比较。

  • 如果有任一操作数是 NaN,则相等操作符返回 false,不相等操作符返回 true。

    即使两个操作数都是 NaN,相等操作符也返回 false,因为按照规则,NaN 不等于 NaN

  • 如果两个操作数都是对象,则比较它们是不是同一个对象。如果两个操作数都指向同一个对象,则相等操作符返回 true。否则,两者不相等。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant