zoukankan      html  css  js  c++  java
  • 迭代器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遍历

  • 相关阅读:
    .net百度编辑器的使用
    phpstudy远程连接mysql
    HDU-2389 Rain on your Parade
    HDU-2768 Cat vs. Dog
    HDU-1151 Air Raid
    HDU-1507 Uncle Tom's Inherited Land*
    HDU-1528/1962 Card Game Cheater
    HDU-3360 National Treasures
    HDU-2413 Against Mammoths
    HDU-1045 Fire Net
  • 原文地址:https://www.cnblogs.com/qianqiang0703/p/13612907.html
Copyright © 2011-2022 走看看