首页 > 其他 > 详细

ES6 Iterator与Generator

时间:2020-12-13 08:14:47      阅读:46      评论:0      收藏:0      [点我收藏+]

一 Iterator

  遍历器(Iterator),它是一种接口,为各种不同的数据结构提供统一的访问机制。。即for...of循环,当使用for...of循环遍历某种数据结构时,该循环会自动去寻找Iterator接口。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)

  1 作用: 

  • 1)是为各种数据结构,提供一个统一的、简便的访问接口  
  • 2)使得数据结构的成员能够按某种次序排列 
  • 3)Iterator接口主要供for...of消费

  2 模拟next方法返回值的例子

 1     //一个遍历器生成函数,作用就是返回一个遍历器对象
 2     function makeIterator(arr){
 3         var index = 0;
 4         return {
 5             next: function() {
 6                if(index<arr.length){
 7                    return {value:arr[index++],done:false}
 8                }else{
 9                    return {value: undefined,done:true}
10                }
11             }
12         }
13     }
14     var it = makeIterator([‘a‘, ‘b‘]);
15     //指针对象的next方法,用来移动指针。
16     //开始时,指针指向数组的开始位置。
17     //然后,每次调用next方法,指针就会指向数组的下一个成员。
18     //第一次调用,指向a;第二次调用,指向b。
19     console.log(it.next())//Iterator.html:21 {value: "a", done: false}
20     console.log(it.next())//{value: "b", done: false}
21     console.log(it.next())//{value: undefined, done: true}

  3 工作原理:

  • 创建一个指针对象,指向数据结构的起始位置。
  • 第一次调用next方法,指针自动指向数据结构的第一个成员
  • 接下来不断调用next方法,指针会一直往后移动,直到指向最后一个成员
  • 每调用next方法返回的是一个包含value和done的对象,{value: 当前成员的值,done: 布尔值}
    • value表示当前成员的值,done对应的布尔值表示当前的数据的结构是否遍历结束。
    • 当遍历结束的时候返回的value值是undefined,done值为true

  4 调用Iterator接口的场合

  • (1)解构赋值,对数组和Set结构进行解构赋值时,会默认调用Symbol.iterator方法。
    • let [first, ...rest] = set;
  • (2)扩展运算符
    • [...str]
  • (3)yield* yield*后面跟的是一个可遍历的结构,它会调用该结构的遍历器接口。
  • (4)for...of Array.from() Map() Set()
 1  //当使用扩展运算符(...)或者对数组和 Set 结构进行解构赋值时,会默认调用Symbol.iterator方法
 2     // 原生具备iterator接口的数据(可用for of遍历)
 3     //数组 字符串  Set
 4     let arr1 = [1, 2, 3, 4];
 5     let arr2 = "kaixin";
 6     let set = new Set(["q","w","e","r","t","y"])
 7     for(let i of arr1){
 8         console.log(i); // 1 2 3  4
 9     }
10     console.log(...arr1) // 1 2 3 4
11     console.log(...arr2) // k a i x i n
12     console.log(...set) //q w e r t y
13     //对象不行 因为本身没有迭代器 会报错
14     var obj = { a: 2, b: 3 }
15     for(let i of obj){
16         console.log(i); // Iterator.html:38 Uncaught TypeError: obj is not iterable
17     }
18     //让对象支持for…of的办法就是手动给对象添加迭代器
19     obj[Symbol.iterator] = function(){
20         const _this = this
21         const keys = Object.keys(this)
22         let index = 0
23         return {
24             next(){
25                 return {
26                     value: _this[keys[index++]],
27                     done: index>keys.length
28                 }
29             }
30         }
31     }
32     for(let i of obj){
33         console.log(i); // 2,3
34     }

二 Generator 

ES6 Iterator与Generator

原文:https://www.cnblogs.com/willowTree/p/14127433.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!