迭代器iterator

迭代器  Symbol.iterator

  要想能够被for...of正常遍历的,都需要实现一个遍历器Iterator。而数组,Set和Map结构,早就内置好了遍历器Iterator(又叫迭代器),它们的原型中都有一个Symbol.iterator方法;而Object对象并没有实现这个接口,使得它无法被for...of遍历.

 

原理:

  当可遍历对象被for...of遍历的时候,[Symbol.iterator]()就会被调用,返回一个iterator对象。其中还有一个很重要的方法:next( )。遍历器上不断调用next( )方法,直到done的值为true的时候,就表示遍历完成结束了

 

实现:

  

 1 <script>
 2     let Person = {
 3         name: '姓名哦',
 4         age: 65,
 5     }
 6     // 添加迭代器
 7     Person[Symbol.iterator] = function () {
 8         let index = 0;
 9         let keys = Object.keys(this);
10         return {
11             next: () => {
12                 let value = {
13                     key: keys[index],
14                     value: this[keys[index]]
15                 }
16                 let done = index === keys.length;
17                 index++;
18                 return {
19                     value,
20                     done
21                 }
22             }
23         }
24 
25     }
26     for (const item of Person) {
27         console.log(item);
28     }
29 </script>

 iterator实现的价值

  新特性for...of之所以能够遍历各种不同的数据结构,正是因为这个数据结构都实现了Iterator遍历器接口,供for...of遍历

posted @ 2020-09-04 11:37  赛德·乌漆嘛黑  阅读(151)  评论(0编辑  收藏  举报