-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcoercion.js
75 lines (62 loc) · 2.4 KB
/
coercion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* 强制类型转换:
* 将某个值的类型转换成其他类型通常叫做 “类型转换”,在执行过程中,转换会隐式强制执行
*
* == vs ===
* 除了 恒等操作 (===) 会对双方类型验证,相等操作 (==) 会对双方进行强制类型转换以外,在其他方面的表现一致
*
* == 会对双方进行必要的强制类型转换,之后再比较 value
* === 不会进行转换,因此如果两个值的类型不同则直接返回 false
* 因此,=== 的比较会更快,而且可能和 == 的结果不一样
*
* 参考资料:
* http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons
* http://davidwalsh.name/fixing-coercion#isnt-coercion-already-dead
* http://bytearcher.com/articles/equality-comparison-operator-javascript/
* http://rainsoft.io/the-legend-of-javascript-equality-operator/
* http://bytearcher.com/articles/equality-comparison-operator-javascript/
*
* 译者注:
* 补充一份资料:
* 一张图彻底搞懂JavaScript的==运算
* https://zhuanlan.zhihu.com/p/21650547
*/
// JS 中的强制类型转换
(function () {
var x = 42;
var y = x + ""; // 隐式转换
console.log(y); // "42"
var z = String(x); // 显式转换
console.log(z); // "42"
})();
// Equality checks - Crazyyy Sh*t!!! 我也觉得😂
(function () {
console.log('' == '0'); // false
console.log(0 == ''); // true
console.log(0 == '0'); // true
console.log(false == 'false'); // false
console.log(false == '0'); // true
console.log(false == undefined); // false
console.log(false == null); // false
console.log(null == undefined); // true
console.log(' \t\r\n ' == 0); // true
// Array
var a = [1, 2, 3];
var b = [1, 2, 3];
console.log(a == b); // false
console.log(a === b); // false
// Object
var c = {x: 1, y: 2};
var d = {x: 1, y: 2};
console.log(c == d); // false
console.log(c === d); // false
// String
var e = "text";
var f = "te" + "xt";
console.log(e == f); // true
console.log(e === f); // true
// == 操作检查两个对象的值,并返回 true
// === 检测到两者不是同样的对象,返回 false
console.log("abc" == new String("abc")); // true
console.log("abc" === new String("abc")); // false
})();