一 Iterator
遍历器(Iterator),它是一种接口,为各种不同的数据结构提供统一的访问机制。。即for...of循环,当使用for...of循环遍历某种数据结构时,该循环会自动去寻找Iterator接口。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)
1 作用:
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 工作原理:
4 调用Iterator接口的场合
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
原文:https://www.cnblogs.com/willowTree/p/14127433.html