zoukankan      html  css  js  c++  java
  • iterator迭代器

    一、概念

    1. 为所有的数据结构提供统一的访问方式。
    2. 接口对象一共有3个方法,next()方法、return()方法、throw()方法。
    3. next() 必填

      用于for..of迭代。

      该方法返回一个对象{value,done}。 value:元素值,done:状态位,用于指定循环是否结束。

    4. 所谓迭代器,其实就是一个具有 next() 方法的对象,每次调用 next() 都会返回一个结果对象,该结果对象有两个属性,value 表示当前的值,done 表示遍历是否结束。
    5. 一个数据结构只要具有 Symbol.iterator 属性,就可以认为是"可遍历的"(iterable)。
    6. 对象没有
      // 接 for of 遍历一个对象,会报错,
      const obj = {
          value: 1
      };
      
      for (value of obj) {
          console.log(value);
      }
      
      // TypeError: iterator is not iterable


      // 然而如果我们给该对象添加 Symbol.iterator 属性:
      obj[Symbol.iterator] = function() {
          return createIterator([1, 2, 3]);
      };
      
      for (value of obj) {
          console.log(value);
      }
      
      // 1
      // 2
      // 3

        

    7. 默认可遍历的有
      const colors = ["red", "green", "blue"];
      
      for (let color of colors) {
          console.log(color);
      }
      
      // red
      // green
      // blue
      

        

      • 数组
      • Set
      • Map
      • 类数组对象,如 arguments 对象、DOM NodeList 对象
      • Generator 对象
      • 字符串

    8. 内建迭代器

      但有的时候不仅需要使用值,还需要使用索引,

      ES6 为数组、Map、Set 集合内建了以下三种迭代器:
      1. entries() 返回一个遍历器对象,用来遍历[键名, 键值]组成的数组。对于数组,键名就是索引值。
      2. keys() 返回一个遍历器对象,用来遍历所有的键名。
      3. values() 返回一个遍历器对象,用来遍历所有的键值。
        var colors = ["red", "green", "blue"];
        
        for (let index of colors.keys()) {
            console.log(index);
        }
        
        // 0
        // 1
        // 2
        
        for (let color of colors.values()) {
            console.log(color);
        }
        
        // red
        // green
        // blue
        
        for (let item of colors.entries()) {
            console.log(item);
        }
        
        // [ 0, "red" ]
        // [ 1, "green" ]
        // [ 2, "blue" ]
        

          

  • 相关阅读:
    细节决定成败,为什么他能挣15亿
    GLSL Notes
    Connecting Physics Bodies
    Pylint
    Physicals
    Advanced Scene Processing
    Working with Other Node Types II
    OperateParticleWithCodes
    SpriteParticle II
    Working with Other Node Types
  • 原文地址:https://www.cnblogs.com/anbozhu7/p/11819995.html
Copyright © 2011-2022 走看看