We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
==
个人认为这是 JavaScript 里面一个很迷的操作符,为什么?你理解下面的代码究竟发生了什么吗?
"42" == 42; // true "0" == false; // true 2 == [2]; // true [] == 0; // true [] == ![]; // true
It's crazy.
感觉这个操作符有很多内涵,很迷。
可以看 ES5.1 11.9.3 了解 == 的算法。
JavaScript 里面呢,有两种形式的类型转换,一种是显式转换 "type casting",一种是隐式转换 "coercion"。
显式转换比如:
var a = 42; var b = String(a); b; // "42"
注意 上面没有 new。
new
隐式转换比如:
var a = [1, 2]; var b = [3, 4]; a + b; // "1,23,4"
很迷,不是吗?
应该有很多人会认为:== 只比较值,而 === 既比较值又比较类型。这让人看起来好像 === 做的工作更多。
===
但其实== 与 === 的区别是: ** == 允许进行类型转换,=== 不允许类型转换。所以应该是 == 进行的步骤会更多。**
根据规范我们来剖析一下开头的例子究竟为什么会这样。
例1:
"42" == 42; // true
"42"
42
例2:
"0" == false; // true
false
0
例3:
2 == [2]; // true
[2]
ToPrimitive
"2"
例4:
[] == 0; // true
[]
""
例5:
[] == ![]; // true
![]
嗯…我知道这很难记住,所以在实际生产中,即使你很了解隐式转换,但是出于代码可读性的考虑,别装*,尽量用 ===。
那你知道为什么:
!""; // true !" "; // false
var a = { b: 42 }; var b = { b: 43 }; a < b; // false a == b; // false a > b; // false a <= b; // true a >= b; // true
自己想去吧~
The text was updated successfully, but these errors were encountered:
No branches or pull requests
JavaScript
==
个人认为这是 JavaScript 里面一个很迷的操作符,为什么?你理解下面的代码究竟发生了什么吗?
It's crazy.
感觉这个操作符有很多内涵,很迷。
可以看 ES5.1 11.9.3 了解
==
的算法。JavaScript 里面呢,有两种形式的类型转换,一种是显式转换 "type casting",一种是隐式转换 "coercion"。
显式转换比如:
注意 上面没有
new
。隐式转换比如:
很迷,不是吗?
应该有很多人会认为:
==
只比较值,而===
既比较值又比较类型。这让人看起来好像===
做的工作更多。但其实
==
与===
的区别是:**
==
允许进行类型转换,===
不允许类型转换。所以应该是==
进行的步骤会更多。**根据规范我们来剖析一下开头的例子究竟为什么会这样。
例1:
"42"
转换为42
例2:
false
转换为0
例3:
[2]
经过ToPrimitive
转换为"2"
例4:
[]
转换为""
""
转换为0
例5:
![]
转换为false
false
转换为0
嗯…我知道这很难记住,所以在实际生产中,即使你很了解隐式转换,但是出于代码可读性的考虑,别装*,尽量用
===
。那你知道为什么:
自己想去吧~
The text was updated successfully, but these errors were encountered: