Skip to content
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

JavaScript == #59

Open
beiweiqiang opened this issue Nov 11, 2016 · 0 comments
Open

JavaScript == #59

beiweiqiang opened this issue Nov 11, 2016 · 0 comments

Comments

@beiweiqiang
Copy link
Contributor

JavaScript ==

个人认为这是 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

隐式转换比如:

var a = [1, 2];
var b = [3, 4];
a + b; // "1,23,4"

很迷,不是吗?

应该有很多人会认为:== 只比较值,而 === 既比较值又比较类型。这让人看起来好像 === 做的工作更多。

但其实===== 的区别是:
** == 允许进行类型转换,=== 不允许类型转换。所以应该是 == 进行的步骤会更多。**

根据规范我们来剖析一下开头的例子究竟为什么会这样。

例1:

"42" == 42; // true
  1. "42" 转换为 42
  2. 成立

例2:

"0" == false; // true
  1. false 转换为 0
  2. 参照例1

例3:

2 == [2]; // true
  1. [2] 经过 ToPrimitive 转换为 "2"
  2. 例 1

例4:

[] == 0; // true
  1. [] 转换为 ""
  2. "" 转换为 0
  3. 成立

例5:

[] == ![]; // true
  1. ![] 转换为 false
  2. false 转换为 0
  3. 例4

嗯…我知道这很难记住,所以在实际生产中,即使你很了解隐式转换,但是出于代码可读性的考虑,别装*,尽量用 ===

那你知道为什么:

!""; // 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

自己想去吧~

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

2 participants