js css html深入JavaScript

深入JavaScript Day22 - 迭代器、可迭代对象、i

2022-01-25  本文已影响0人  望穿秋水小作坊

一、迭代器、可迭代对象

1、【重要】一句话概括什么是迭代器?迭代器模式的优点是什么?

image.png

2、手写一个最简单的迭代器对象,理解迭代器对象?

let names = ["aaa", "bbb", "ccc"];

let index = 0;
let namesIterator = {
  next: function () {
    if (index < names.length) {
      return { done: false, value: names[index++] };
    } else {
      return { done: true, value: undefined };
    }
  },
};

console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());

3、【迭代器】和【可迭代对象】之间是什么关系(一句话概括)?

image.png

4、手写可迭代对象?

const obj = {
  names: ["aaa", "bbb", "ccc"],
  [Symbol.iterator]: function () {
    let index = 0;
    return {
      next: () => {
        if (index < this.names.length) {
          return { done: false, value: this.names[index++] };
        } else {
          return { done: true, value: undefined };
        }
      },
    };
  },
};
const iterator = obj[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

image.png

5、为什么一个普通的const obj = {names: ["aaa", "bbb", "ccc"]}对象,无法调用for...of语法?

// 会有如下报错
for (const item of obj) {
                             ^
TypeError: obj is not iterable

二、生成器

1、什么是生成器(generator,一句话概括)?生成器和迭代器有关系吗?

2、【学习技巧】凡是遇到【新知识】,被定义成【旧知识】的特殊情况,我们该怎么学习【新知识】呢?

3、生成器和生成器函数有什么关系?如何定义一个生成器函数?

image.png

4、yield* 是什么作用?

class Room {
  constructor(address, students) {
    this.students = students;
    this.address = address;
  }
  foo = function () {
    console.log("foo");
  };

  [Symbol.iterator] = function* () {
    yield* this.students;
  };
}

const room2 = new Room("逸夫楼", ["zhansan", "lisi", "wangwu"]);

for (const stu of room2) {
  console.log(stu);
}

5、一个能传参、能拿返回值、能分段执行的生成器函数?

function* foo(prama1) {
  console.log("foo函数第一段");
  let value1 = 100;
  const prama2 = yield value1 + prama1;

  console.log("foo函数第二段");
  let value2 = 200;
  const prama3 = yield value2 + prama2;

  console.log("foo函数第三段");
  let value3 = 300;
  const prama4 = yield value3 + prama3;

  console.log("foo函数第四段");
  let value4 = 400 + prama4;
  return value4;
}

const generator = foo(10);

console.log(generator.next());
console.log(generator.next(20));
console.log(generator.next(30));
console.log(generator.next(40));
console.log(generator.next(50));
foo函数第一段
{ value: 110, done: false }
foo函数第二段
{ value: 220, done: false }
foo函数第三段
{ value: 330, done: false }
foo函数第四段
{ value: 440, done: true }
{ value: undefined, done: true }
上一篇 下一篇

猜你喜欢

热点阅读