一.iterator
1.概念:iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制。
2.作用:
-
为各种数据结构,提供一个统一的、简便的访问接口;
-
使得数据结构的成员能够按某种次序排列。
-
ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费。
3.工作原理:
-
创建一个指针对象,指向数据结构的起始位置。
-
第一次调用next方法,指针自动指向数据结构的第一个成员
-
接下来不断调用next方法,指针会一直往后移动,直到指向最后一个成员
-
每调用next方法返回的是一个包含value和done的对象,{value: 当前成员的值,done: 布尔值}
-
value表示当前成员的值,done对应的布尔值表示当前的数据的结构是否遍历结束。
-
当遍历结束的时候返回的value值是undefined,done值为false
-
4.原生具备iterator接口的数据(可用for of遍历)
-
Array
-
arguments
-
set容器
-
map容器
-
String
-
......
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 }

5.模拟实现iterator接口
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