-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# 遍历器 迭代器 | ||
> 遍历器就是第一个对象,这个对象有一个 `next` 方法,会返回需要的数据,可遍对象就是那些部署了 `Symbol.iterator` 属性的对象。我们也可以通过 `[].entries()` 获取到数组的遍历器 | ||
```js | ||
const colors = ['red', 'blue', 'green']; | ||
// 这里的 `iterator` 就是遍历器 | ||
const iterator = colors[Symbol.iterator](); | ||
// `iterator` 上面有个一 `next` 方法,每一次执行都会返回一个对象,包含一个 `name` 属性记录值和一个 `done` 属性记录遍历是否完结。 | ||
iterator.next(); // {value: "red", done: false} | ||
``` | ||
|
||
### 构建数组中的 `values` 方法 | ||
目前的浏览器上只有 `[].keys()` 这个方法,返回的就是一个遍历器对象,我们可以自己尝试构建一个 `[].values()` 方法 | ||
```js | ||
const colors = ['red', 'blue', 'green']; | ||
Array.prototype.values = function () { | ||
let i = 0; | ||
let items = this; | ||
return { | ||
next() { | ||
const done = i >= items.length; | ||
const value = done ? undefined : items[i++]; | ||
return { | ||
value, | ||
done | ||
} | ||
} | ||
} | ||
} | ||
``` |