es6 Iterator



  • Iterator和for...of循环

    Iterator的概念

    • JavaScript表示“集合”的数据结构

      • Array
      • Object
      • Map
      • Set

      我们需要一种统一的接口机制来处理不同的数据结构,因此就出现了遍历器Iterator

    • Iterator如何遍历

      • 创建一个指针对象,指向当前数据结构的起始位置
      • 第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员
      • 每次调用该指针对象的next的方法,都可以将指针指向数据结构的下一个成员
      • 当指针对象指向数据结构的结束位置,遍历结束
    • next方法的返回值

      • value:当前成员的值
      • done:布尔值,表示遍历是否结束
    • 迭代过程

      • 通过Symbol.iterator创建一个迭代器,指向当前数据结构起始位置
      • 通过next方法进行向下迭代
      const items = ["zero", "one", "two"];
      const it = items[Symbol.iterator]();
      console.log(it.next());
      
    • 可使用for...of循环迭代的数据结构

      • Array
      • String
      • Map
      • Set
      • DOM元素
      /* 数组的遍历 */
      for(let item of [1, 2, 3, 4, 5]) {
          console.log(item);
      }
      /* 字符串的遍历 */
      for(let c of "zabcde") {
          console.log(c);
      }
      /* map的遍历 */
      var map = new Map();
      map.set(0, "zero");
      map.set(1, "one");
      map.set(2, "two");
      //遍历键值对
      for (let [key, value] of map) {
        console.log(key + " = " + value);
      }
      //遍历键
      for (let key of map.keys()) {
        console.log(key);
      }
      //遍历值
      for (let value of map.values()) {
        console.log(value);
      }
      /* Set的遍历 */
      let set = new Set();
      set.add(1);
      set.add(3);
      set.add(5);
      for(let item of set) {
        console.log(item);
      }
      

    async函数


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

与 Dian 的连接断开,我们正在尝试重连,请耐心等待