1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(array): edit spread

This commit is contained in:
ruanyf 2019-01-08 22:17:08 +08:00
parent 39a66bd66f
commit 7791c64d30
2 changed files with 23 additions and 14 deletions

View File

@ -58,7 +58,7 @@ const arr = [
// [1]
```
注意扩展运算符如果放在括号中JavaScript 引擎就会认为这是函数调用,否则就会报错。
注意扩展运算符如果放在括号中JavaScript 引擎就会认为这是函数调用。如果这时不是函数调用,就会报错。
```javascript
(...[1, 2])
@ -66,9 +66,12 @@ const arr = [
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
console.log(...[1, 2])
// 1 2
```
上面两种情况都会报错,因为扩展运算符所在的括号不是函数调用,而`console.log(...[1, 2])`就不会报错,因为这时是函数调用。
上面两种情况都会报错,因为扩展运算符所在的括号不是函数调用,而第三种情况`console.log(...[1, 2])`就不会报错,因为这时是函数调用。
### 替代函数的 apply 方法
@ -282,7 +285,7 @@ str.split('').reverse().join('')
**5实现了 Iterator 接口的对象**
任何 Iterator 接口的对象(参阅 Iterator 一章),都可以用扩展运算符转为真正的数组。
任何定义了遍历器Iterator接口的对象(参阅 Iterator 一章),都可以用扩展运算符转为真正的数组。
```javascript
let nodeList = document.querySelectorAll('div');
@ -291,6 +294,20 @@ let array = [...nodeList];
上面代码中,`querySelectorAll`方法返回的是一个`NodeList`对象。它不是数组,而是一个类似数组的对象。这时,扩展运算符可以将其转为真正的数组,原因就在于`NodeList`对象实现了 Iterator 。
```javascript
Number.prototype[Symbol.iterator] = function*() {
let i = 0;
let num = this.valueOf();
while (i < num) {
yield i++;
}
}
console.log([...5]) // [0, 1, 2, 3, 4]
```
上面代码中,先定义了`Number`对象的遍历器接口,扩展运算符将`5`自动转成`Number`实例以后,就会调用这个接口,就会返回自定义的结果。
对于那些没有部署 Iterator 接口的类似数组的对象,扩展运算符就无法将其转为真正的数组。
```javascript

View File

@ -455,15 +455,7 @@ obj.foo() // "world"
## 对象的扩展运算符
《数组的扩展》一章中,已经介绍过扩展运算符(`...`)。
```javascript
const [a, ...b] = [1, 2, 3];
a // 1
b // [2, 3]
```
ES2018 将这个运算符[引入](https://github.com/sebmarkbage/ecmascript-rest-spread)了对象。
《数组的扩展》一章中,已经介绍过扩展运算符(`...`。ES2018 将这个运算符[引入](https://github.com/sebmarkbage/ecmascript-rest-spread)了对象。
### 解构赋值