ES6遍历器 生成器 学习整理

遍历器[迭代器](Iterator)

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

Iterator 的作用有三个:

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

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

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

示例代码

//迭代器示例
function  newIterator(arr) {
  let index = 0;

  return {
    next:()=>{
      if(index<arr.length){
        return {value:arr[index++]}
      }
      return {value:'无数据值'}
      
    }
  }
}

const nit=newIterator(['第一次','第二次','第三次']);

console.log( nit.next().value)
console.log( nit.next().value)
console.log( nit.next().value)
console.log( nit.next().value)
console.log( nit.next().value)


/**
输出结果

第一次
第二次
第三次
无数据值
无数据值
**/
给某一实例增加迭代器

Symbol.iterator属性本身是一个函数,就是当前数据结构默认的遍历器生成函数。执行这个函数,就会返回一个遍历器。至于属性名Symbol.iterator,它是一个表达式,返回Symbol对象的iterator属性,这是一个预定义好的、类型为 Symbol 的特殊值,所以要放在方括号内

Symbol 是 ES6 引入了一种新的原始数据类型Symbol,表示独一无二的值

const obj = {
  [Symbol.iterator] : function () {
    return {
      next: function () {
        return {
          value: 1,
          done: true
        };
      }
    };
  }
};

生成器函数 Generator

生成器函数语法可以理解为对迭代器简化,为了更便捷的使用迭代器而出现的生成器函数。用来达到语法层面的代码精简;

Generator 可以看作是数据结构,更确切地说,可以看作是一个数组结构,因为 Generator 函数可以返回一系列的值,这意味着它可以对任意表达式,提供类似数组的接口。

示例代码

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

var hw = helloWorldGenerator();

/** 执行结果
hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true }
**/

for...of循环可以自动遍历 Generator 函数时生成的Iterator对象,且此时不再需要调用next方法。

原文地址:https://www.cnblogs.com/QQ-Monarch/p/8392688.html