1. 迭代器
# 1. 迭代器
迭代器(Iterator)就是一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作
# 1.1 介绍
ES6创造了一种新的遍历命令
for...of循环,其是一种数据统一遍历方式。Iterator接口主要供for...of消费原生具备 iterator 接口的数据 (可用
for...of遍历 )- a) Array
 - b) Arguments
 - c) Set
 - d) Map
 - e) String
 - f) TypedArray
 - g) NodeList
 
# 1.2 工作原理
- 创建一个指针对象,指向当前数据结构的起始位置
 - 第一次调用对象的 
next方法,指针自动指向数据结构的第一个成员 - 接下来不断调用 
next方法,指针一直往后移动,直到指向最后一个成员 - 每调用 
next方法返回一个包含value和done属性的对象 
const xiyou = ['唐僧', '孙悟空', '猪八戒', '沙僧'];
let iterator = xiyou[Symbol.iterator]();
console.log(iterator.next()); // {value: "唐僧", done: false}
console.log(iterator.next()); // {value: "孙悟空", done: false}
console.log(iterator.next()); // {value: "猪八戒", done: false}
console.log(iterator.next()); // {value: "沙僧", done: false}
console.log(iterator.next()); // {value: undefined, done: true}
# 1.3 应用——自定义遍历数据
const banji = {
	name: '终极一班',
	stus: [
		'xiaoming',
		'xiaoning',
		'xiaotian',
		'knight'
	],
	[Symbol.iterator](){
		let index = 0;
		let _this = this;
		return {
			next: function(){
				if(index < _this.stus.length){
					const result = { value: _this.stus[index], done: false }
					index++;
					return result;
				}else{
					return {value: undefined, done: true}
				}
			}	
		};
	}
}
for(let v of banji) {
	console.log(v);  
}
// 'xiaoming','xiaoning','xiaotian','knight'
const obj = {
  store: ['foo', 'bar', 'baz']
  [Symbol.iterator]: function() {
    let index = 0
    const self = this
    return {
      next: function(){
        const result = {
          value: self.store[index],
          done: index >= self.store.length
        }
        index++
        return result
      }
    }
  }
}
再次简写
const obj = {
  store: ['foo', 'bar', 'baz']
  [Symbol.iterator]: function() {
    let index = 0
    const self = this
    return {
      next: function(){
        return {
          value: self.store[index],
          done: index++ >= self.store.length
        }
      }
    }
  }
}
# 迭代器模式
对外提供统一的遍历接口,不用关心其内部数据结构