es6 语法 (iterator和for...of循环)

Iterator遍历器

遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。

作用:

  • 为各种数据结构,提供一个统一的、简便的访问接口
  • 使得数据结构的成员能够按某种次序排列
  • ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费

Iterator的遍历过程:

(1)创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。

(2)第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。

(3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。

(4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。

在ES6中,有三类数据结构原生具备Iterator接口:数组、某些类似数组的对象、Set和Map结构。

可以覆盖原生的Symbol.iterator方法,达到修改遍历器行为的目的。

for...of

for...of循环可以使用的范围包括数组、Set和Map结构、某些类似数组的对象(比如arguments对象、DOM NodeList对象)、后文的Generator对象,以及字符串。


{
  let arr=['hello','world'];
  let map=arr[Symbol.iterator]();
  //done表示是否还有下一步了,false有 true 没有
  console.log(map.next()); //{value: "hello", done: false}
  console.log(map.next()); //{value: "world", done: false}
  console.log(map.next()); //{value: undefined, done: true}
}

{
  let obj={
    start:[1,3,2],
    end:[7,9,8],
    //声明
    [Symbol.iterator](){
      //函数体
      let self=this;
      let index=0; //当前遍历索引
      let arr=self.start.concat(self.end); //合并数组
      let len=arr.length;//记住数组长度
      return {
        //iterator部署的时候一定要有next这个方法
        next(){
          //遍历过程
          if(index<len){
            return {
              value:arr[index++],
              done:false
            }
          }else{
            return {
              value:arr[index++],
              done:true //遍历结束
            }
          }
        }
      }
    }
  }
  //验证接口是否部署成功
  for(let key of obj){
    console.log('key1',key); //1 3 2 7 9 8
  }
}

{
  let arr=['hello','world'];
  for(let value of arr){
    console.log('value',value); //hello ,world
  }
}
原文地址:https://www.cnblogs.com/Byme/p/7725358.html