迭代器 | 青训营笔记

57 阅读2分钟

这是我参与「 第五届青训营 」伴学笔记创作活动的第 12 天 迭代器

  1. 如果⼀个对象可以使⽤户遍历容器对象, 那么它就是迭代 器
  2. 在JavaScript中,迭代器也是⼀个具体的对象,这个对象 需要符合迭代器协议, 迭代器协议定义了产⽣⼀系列值(⽆ 论是有限还是⽆限个)的标准⽅式, 在JavaScript中这个标 准就是⼀个特定的next⽅法
  3. next⽅法有如下的要求
  4. ⼿写迭代器 ⼀个⽆参数或者⼀个参数的函数,返回⼀个应当拥有以下两个属性的对象 done(boolean) 如果迭代器可以产⽣序列中的下⼀个值,则为 false。(这等价于没有指定 done 这个属性。) ✓ 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。 value 迭代器返回的任何 JavaScript 值。done 为 true 时可省略。

给数组创建⼀个迭代器

let index = 0
const nameIterator = {
  next: function () {
    //doone: Boolean
    //value: 具体值/undefined
    if (index < names.length) {
      return {
        done: false,
        value: names[index++]
      }
    } else {
      return {
        done: true
      }
    }
  }
}
 

给infos创建⼀个迭代器, 迭代infos中的friends

let index = 0
const infosIterator = {
  next: function () {
    if (index < infos.friends.length) {
      return {
        done: false,
        value: infos.friends[index++]
      }
    } else {
      return { done: true }
    }
  }
}

把对象和迭代器放在⼀起

const infos = {
  friends: ['kobe', 'james', 'curry'],
  [Symbol.iterator]: function () {
    let index = 0
    const infosIterator = {
      next: function () {
        if (index < infos.friends.length) {
          return { done: false, value: infos.friends[index++] }
        } else {
          return { done: true }
        }
      }
    }
  }
}

1. 实现⼀个特定的函数[Symbol.iterator]

2. 这个函数需要返回⼀个迭代器, 这个迭代器⽤于迭代当前的对象

⽣成器

  1. ⽣成器函数也是⼀个函数,但是和普通的函数有⼀些区 别: ⾸先,⽣成器函数需要在function的后⾯加⼀个符号:* 其次,⽣成器函数可以通过yield关键字来控制函数的执⾏流程: 最后,⽣成器函数的返回值是⼀个Generator (⽣成器对象)
const names = ['abc', 'cba', 'nba']
const nums = [1, 2, 3, 4, 5]
function* createArrayIterator(arr) {
  yield* arr
}
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next())