Skip to content

Commit

Permalink
迭代器 遍历器
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 26, 2017
1 parent 026904a commit d156eb8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 17.classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,34 @@ class Dog extends Animal{
}

const hot = new Dog('hot',2);
```

### 拓展内建对象数组
> 在 ES6 之前,我们很难在内建对象的基础上扩建自己的类。 ES6 的 Class 采用了另一种机制来解决这个问题。
```js
class MovieCollection extends Array {
constructor(name, ...items) {
super(...items);
this.name = name;
}

add(movie) {
this.push(movie);
}

topRated(limit = 3) {
return this.sort((a, b) => a.score < b.score).slice(0, limit);
}
}

const movies = new MovieCollection('favorite movies',
{ name: 'The Croods', score: 8.7 },
{ name: 'The Shawshank Redemption', score: 9.6 },
{ name: 'Leon', score: 9.3 },
{ name: 'Days of summer', score: 8.0 },
);

movies.push({ name: '功夫熊猫', score: 9.7 })

console.log(movies.topRated());
```
30 changes: 30 additions & 0 deletions 18.iterator.md
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
}
}
}
}
```

0 comments on commit d156eb8

Please sign in to comment.