JS中的“==”符号及布尔值转换规则

JS中的“==”符号及布尔值转换规则

 

what are the rules for how == converts types?

关于"=="的比较规则:

1. Comparing numbers and strings will always convert the strings to numbers. 

number类型与string类型比较,string会转换为number类型。如:2=="2" true

2. null and undefined will always equal each other.

null类型与undefined类型比较始终相等。如:var a = null,b; 则 a==b 为true。

3. Comparing booleans to any other type will always cause the booleans to be converted to numbers.

布尔类型与其他任何类型进行比较,布尔类型将会转换为number类型。如:var a = 0, b = false;则a==b为true

4. Comparing numbers or strings to objects will always cause the numbers or strings to be converted to objects.

number类型或者string类型与object类型进行比较,number或者string类型都会转换为object类型。如:var a = 0, b = {};则a==b为false

 

The rules for converting other types to booleans are actually relatively straightforward:

关于其他类型转换为布尔类型的规则:

1. undefined and null are always false.

2. Booleans are just treated as booleans (obviously).

3. Numbers are false if they equal 0 or NaN; otherwise, they’re true.

4. Strings are true, except for the empty string "", which is false.

5. Objects are always true.

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。