js设计模式——迭代器模式

60 阅读1分钟

实际就是遍历,让用户透过特定的接口访问容器中的每一个元素而不用了解底层的实现

根据可迭代协议将一个普通对象变为可迭代对象,

1.添加一个内置的Symbol.interator方法,可迭代对象都有这个方法

2.interator方法中要实现一个next方法,能返回两种状态的对象,可继续迭代和不可继续迭代

两种实现

1.可以用genator生成器函数,自带next方法

2.自己实现next方法

 //for of用来遍历可迭代对象,包括数组,map,set等,不能遍历对象
    const obj = {
      //1.添加一个Symbol.interator方法
      [Symbol.iterator]() {
        // //方法里面实现next方法
        // //1.使用generator函数实现
        // function* foodGenator() {
        //   yield "apple";
        //   yield "banana";
        //   yield "orange";
        // }
        // //创建生成器
        // const food = foodGenator();
        // return food;
        //2.自己实现next方法
        let index = 0;
        const arr = ["apple", "banana", "orange"];
        return {
          next() {
            if (index < arr.length) {
              return {
                //返回的值
                value: arr[index++],
                //可以继续遍历
                done: false,
              };
            } else {
              return {
                //迭代完毕
                done: true,
              };
            }
          },
        };
      },
    };
    for (const iterator of obj) {
      console.log("iterator", iterator);
    }