iterator

概念: iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制

    作用:

      1、为各种数据结构,提供一个统一的、简便的访问接口;

      2、使得数据结构的成员能够按某种次序排列

      3、ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费。

    工作原理:

      - 创建一个指针对象,指向数据结构的起始位置。

      - 第一次调用next方法,指针自动指向数据结构的第一个成员

      - 接下来不断调用next方法,指针会一直往后移动,直到指向最后一个成员

      - 每调用next方法返回的是一个包含value和done的对象,{value: 当前成员的值,done: 布尔值}

        * value表示当前成员的值,done对应的布尔值表示当前的数据的结构是否遍历结束。

        * 当遍历结束的时候返回的value值是undefined,done值为false

    原生具备iterator接口的数据(可用for of遍历)

      1、Array

      2、arguments

      3、set容器

      4、map容器

      5、String

//interator内部分析
function interator(arr) {
                 let index = 0;
                return { //返回一个对象,里面包含next方法指向下一个数值
                  next : function () {
                          return index<arr.length? {value:arr[index++],done:"false"}:{value:arr[index++],done:"true"};
                  }
                }
             }
             let arr = [1,2,3,4,5];
             let inter = interator(arr);
             console.log(inter.next());{value:1,done:"false"}
             console.log(inter.next());
             console.log(inter.next());
             console.log(inter.next());
             console.log(inter.next());
             console.log(inter.next());{value:1,done:"true"}

  

原文地址:https://www.cnblogs.com/love-life-insist/p/9925400.html