1 let arr = [1,2,3]; 2 3 for (let i of arr) { 4 console.log(i); 5 6 } 7 8 let obj = { 9 name: ‘obj1‘ 10 } 11 12 console.log(arr); //array拥有了iterator接口 13 console.log(...arr); //三点运算符用的也是iterator接口 14 console.log(obj); 15 16 for (let i of obj) { 17 console.log(i); //object对象没有iterator接口 18 19 }
1 //模拟实现iterator接口 2 function iteratorUtil(target) { 3 let index = 0; //用来表示指针其实位置 4 return { //返回指针对象 5 next() { //指针对象的next方法 6 return index < target.length ? { 7 value: target[index++], 8 done: false 9 } : { 10 value: target[index++], 11 done: true 12 }; 13 } 14 } 15 } 16 17 //生成一个迭代器对象 18 let arr = [1,2,3]; 19 let iteratorObj = iteratorUtil(arr); 20 console.log(iteratorObj.next().value); 21 console.log(iteratorObj.next().value); 22 console.log(iteratorObj.next().value); 23 console.log(iteratorObj.next().value);
6.实现Object对象的遍历
1 let arr = [1,2,3,4]; 2 3 var obj = {name: ‘kobe‘, age: 40}; 4 // console.log(obj[Symbol.iterator]); // undefined 5 // console.log(arr[Symbol.iterator]); // function 6 7 function mockIterator() { 8 9 let that = this; 10 11 let index = 0; 12 let length = 0; 13 debugger 14 if(that instanceof Array){ 15 length = that.length; 16 return { 17 next: function () { 18 return index < length ?{value: that[index++], done: false}: {value: that[index++], done: true} 19 } 20 } 21 }else { 22 length = Object.keys(that).length 23 let keys = Object.keys(that); 24 return { 25 next: function () { 26 return index < length ?{value: that[keys[index++]], done: false}: {value: that[keys[index++]], done: true} 27 } 28 } 29 } 30 31 } 32 33 34 35 Array.prototype[Symbol.iterator] = mockIterator; 36 Object.prototype[Symbol.iterator] = mockIterator; 37 38 for(let i of arr){ 39 console.log(i); 40 } 41 for(let i of obj){ 42 console.log(i); 43 }
原文:https://www.cnblogs.com/zhihaospace/p/12023987.html