Skip to content

Commit 4df6d09

Browse files
author
YuChengKai
committed
类型转换
1 parent 1e9ffbd commit 4df6d09

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

JS/JS-en.md

+69
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,75 @@ b.name = 'EF'
5050
console.log(a) // EF
5151
```
5252

53+
# Type Conversion
54+
55+
## Converting to Boolean
56+
57+
Other than `undefined``null``false``NaN``''``0``-0`, all of the values, including objects, are converted to `true`.
58+
59+
## Objects to Primitive Types
60+
61+
When objects are converted, `valueOf` and `toString` will be called, respectively in order. These two methods can also be overridden.
62+
63+
```js
64+
let a = {
65+
valueOf() {
66+
return 0
67+
}
68+
}
69+
```
70+
71+
## Arithmetic Operators
72+
73+
Only for additions, if one of the parameters is a string, the other will be converted to the string as well. For all other operations, as long as one of the parameters is a number, the other will be converted to a number.
74+
75+
Additions will invoke three types of type conversions: to primitive types, to numbers, and to string.
76+
77+
```js
78+
1 + '1' // '11'
79+
2 * '2' // 4
80+
[1, 2] + [2, 1] // '1,22,1'
81+
// [1, 2].toString() -> '1,2'
82+
// [2, 1].toString() -> '2,1'
83+
// '1,2' + '2,1' = '1,22,1'
84+
```
85+
86+
Note the expression `'a' + + 'b'` for addition.
87+
88+
```js
89+
'a' + + 'b' // -> "aNaN"
90+
// since ++ 'b' -> NaN
91+
// You might have seen + '1' -> 1
92+
```
93+
94+
## `==` operator
95+
96+
![](https://user-gold-cdn.xitu.io/2018/3/30/16275cb21f5b19d7?w=1630&h=1208&f=png&s=496784)
97+
98+
`toPrimitive` in the above figure is converting objects to primitive types.
99+
100+
`===` is usually recommended to compare to values. However, if you would like to know if a value is `null`, you can use `xx == null`.
101+
102+
Let's take a look at an example `[] == ![] // -> true`. The following explains why the expression evaluates to `true`.
103+
104+
```js
105+
// [] converting to true, then take the opposite to false
106+
[] == false
107+
// with #8
108+
[] == ToNumber(false)
109+
[] == 0
110+
// with #10
111+
ToPrimitive([]) == 0
112+
// [].toString() -> ''
113+
'' == 0
114+
// with #6
115+
0 == 0 // -> true
116+
```
117+
118+
## Comparison Operator
119+
120+
1. If it's an object, `toPrimitive` is used.
121+
2. If it's a string, `unicode` character index is used to compare.
53122

54123
#### Typeof
55124

0 commit comments

Comments
 (0)