JS的ES6的iterator


一.iterator

1.概念:iterator是一種接口機制,為各種不同的數據結構提供統一的訪問機制。

2.作用:

  • 為各種數據結構,提供一個統一的、簡便的訪問接口;

  • 使得數據結構的成員能夠按某種次序排列。

  • ES6創造了一種新的遍歷命令for...of循環,Iterator接口主要供for...of消費。

3.工作原理:

  1. 創建一個指針對象,指向數據結構的起始位置。

  2. 第一次調用next方法,指針自動指向數據結構的第一個成員

  3. 接下來不斷調用next方法,指針會一直往后移動,直到指向最后一個成員

  4. 每調用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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM