迭代器iterator与生成器generator的使用

目录

一、迭代器

1.定义

2.next方法

3.封装生成迭代器函数

4.无限生成器

5.可迭代对象

6.原生可迭代对象

7.自定义类的可迭代性

二、生成器

1.定义

2.通过yield来返回结果

3.生成器传递函数-next函数

4.生成器的return终止执行

5.生成器的throw捕获异常

6.生成器替代迭代器

7.自定义类迭代 – 生成器实现


一、迭代器

1.定义

迭代器(iterator),是确使用户可在容器对象(container,例如链表或数组)上遍访的对象,使用该接口无需关心对象的内部实现细节。

在JavaScript中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议(iterator protocol):

  • 迭代器协议定义了产生一系列值(无论是有限还是无限个)的标准方式;
  • 那么在js中这个标准就是一个特定的next方法;

2.next方法

next方法有如下的要求:

  • 一个无参数或者一个参数的函数,返回一个应当拥有以下两个属性的对象:
  1. done(boolean):如果迭代器可以产生序列中的下一个值,则为 false。 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。
  2. value:迭代器返回的任何 JavaScript 值。done 为 true 时可省略

代码示例:

const names = ["abc", "cba", "nba"]

// 创建一个迭代器来遍历数组
let index = 0
const namesIterator = {
  next: function() {
    if (index < names.length) {
      // 迭代器可以产生序列中的下一个值,则为 false
      return { done: false, value: names[index++] }
    } else {
      // 迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值
      return { done: true, value: undefined }
    }
  }
}

console.log(namesIterator.next()); // { done: false, value: 'abc' }
console.log(namesIterator.next()); // { done: false, value: 'cba' }
console.log(namesIterator.next()); // { done: false, value: 'nba' }
console.log(namesIterator.next()); // { done: true, value: undefined }
console.log(namesIterator.next()); // { done: true, value: undefined }
console.log(namesIterator.next()); // { done: true, value: undefined }

3.封装生成迭代器函数

// 生成迭代器的函数
function createArrayIterator(arr) {
  let index = 0
  return {
    next: function() {
      if (index < arr.length) {
        return {done: false, value: arr[index++]}
      } else {
        return {done: true, value: undefined}
      }
    }
  }
}

const names = ["abc", "cba", "nba"]

const namesIterator = createArrayIterator(names)
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());

4.无限生成器

done永远都不会变true,也就是永远都不会遍历完

// 创建一个无限迭代器
function createNumberIterator() {
  let index = 0
  return {
    next: function() {
      return {done: false, value: index++}
    }
  }
}

const numberIterator = createNumberIterator()
console.log(numberIterator.next());
console.log(numberIterator.next());
console.log(numberIterator.next());
console.log(numberIterator.next());
console.log(numberIterator.next());
console.log(numberIterator.next());
console.log(numberIterator.next());

5.可迭代对象

1.定义

  • 它和迭代器是不同的概念

  • 当一个对象实现了iterable protocol协议时,它就是一个可迭代对象

  • 这个对象的要求是必须实现 @@iterator 方法,在代码中我们使用 Symbol.iterator 访问该属性

注意:迭代器和可迭代对象是两个完全不同的概念

// 创建一个可迭代对象来访问数组
const iterableObj = {
  names: ["abc", "cba", "nba"],
  [Symbol.iterator]: function() {
    let index = 0
    return {
      // 必须为箭头函数 他才能用this往上层作用域找到name属性
      next: () => {
        if (index < this.names.length) {
          return {done: false, value: this.names[index++]}
        } else {
          return {done: true, value: undefined}
        }
      }
    }
  }
}

6.原生可迭代对象

我们平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象的:String、Array、Map、Set、arguments对象、NodeList集合

应用场景:

  • JavaScript中语法:for ...of、展开语法(spread syntax)、yield*、解构赋值(Destructuring_assignment)
  • 创建一些对象时:new Map([Iterable])、new WeakMap([iterable])、new Set([iterable])、new WeakSet([iterable]);
  • 一些方法的调用:Promise.all(iterable)、Promise.race(iterable)、Array.from(iterable);

代码示例:

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

}

const names = ["abc", "cba", "nba"]

// 1.for of

// 2.展开语法
const arr = [...names, ...iterableObj]
console.log(arr);

// 3.解构赋值
const [name1, name2, name3] = arr
console.log(name1, name2, name3);

// 4.new Set
const set = new Set(names)
console.log(set);

// 5.Promise.all
Promise.all(iterableObj).then(res => {
  console.log(res);
})

7.自定义类的可迭代性

如果我们也希望自己的类创建出来的对象默认是可迭代的,那么在设计类的时候我们就可以添加上 @@iterator 方法;

代码示例:

class Person {
  constructor(address, name, students) {
    this.address = address
    this.name = name
    this.students = students
  }
  entry(newStudent) {
    this.students.push(newStudent)
  }
  // 创建可迭代器
  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        if(index < this.students.length) {
          return {done: false, value: this.students[index++]}
        } else {
          return {done: true, value: undefined}
        }
      },
      // 迭代器中断
      return() {
        console.log("迭代器提前终止了");
        return {done: true}
      }
    }
  }
}

// 创建出来的stu是可迭代的
const stu = new Person("文科楼301", "计算机教室", ["kobe", "james", "curry", "kk"])
// 可以使用for...of来遍历
for (const item of stu) {
  console.log(item);
  if (item === "curry") {
    break
  }
}

二、生成器

1.定义

生成器是ES6中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执 行等,平时我们会编写很多的函数,这些函数终止的条件通常是返回值或者发生了异常

生成器也是一个函数,但是他和普通函数的区别:

  • 首先, 生成器函数需要在function的后面加一个符号:*

  • 其次,生成器函数可以通过yield关键字来控制函数的执行流程:

  • 最后,生成器函数的返回值是一个Generator(生成器):

    • 生成器事实上是一种特殊的迭代器,可以调用next

    • MDN:Instead, they return a special type of iterator, called a Generator

一个yield上面的代码为一段代码

// 生成器函数需要在function的后面加一个符号:*
function* foo() {
  const value1 = 100
  console.log("第一段代码:", value1);
  // 生成器函数可以通过yield关键字来控制函数的执行流程
  yield

  const value2 = 200
  console.log("第二段代码:", value2);
  yield

  const value3 = 300
  console.log("第三段代码:", value3);
  yield
}

// 生成器函数的返回值是一个Generator(生成器)
// 生成器事实上是一种特殊的迭代器
const generator = foo()
generator.next()
generator.next()
generator.next()

2.通过yield来返回结果

迭代器的next是会有返回值的,但是我们很多时候不希望next返回的是一个undefined,这个时候我们可以通过yield来返回结果

function* foo() {
  const value1 = 100
  console.log("第一段代码:", value1);
  // 使用yield来返回结果
  yield value1

  const value2 = 200
  console.log("第二段代码:", value2);
  yield value2

  const value3 = 300
  console.log("第三段代码:", value3);
  yield value3

  return '123'
}

const generator = foo()
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());

3.生成器传递函数-next函数

next接收一个参数(也只能接收一个参数)

function* foo(num) {

  const value1 = 100 * num
  console.log("第一段代码:", value1);
  // 使用yield来返回结果
  const n = yield value1

  // 这里的n是上一个yield的返回值 相当于 const n = yield value1 然后通过next(10) 再将参数10赋值给n
  const value2 = 200 * n
  console.log("第二段代码:", value2);
  const m = yield value2

  const value3 = 300 * m
  console.log("第三段代码:", value3);
  yield value3

  return '123'
}
const generator = foo(10)
/**
 * 第一段代码: 1000
   { value: 1000, done: false }
 */
console.log(generator.next());
/**
 * 第二段代码: 4000
   { value: 4000, done: false }
 */
console.log(generator.next(20));
/**
 * 第三段代码: 9000
   { value: 9000, done: false }
 */
console.log(generator.next(30));
// { value: '123', done: true }
console.log(generator.next());
// { value: undefined, done: true }
console.log(generator.next());

4.生成器的return终止执行

return传值后这个生成器函数就会结束,之后调用next不会继续生成值了

const generator = foo(10)

console.log(generator.next());
// 第二段代码执行 相当于在第一段代码后面加上return 然后第二段代码及后面的都不会执行
console.log(generator.return(15)); // { value: 15, done: true }
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());

5.生成器的throw捕获异常

当抛出异常后,我们使用try...catch来捕获异常,下面的代码可以继续执行

function* foo() {
  const value1 = 100
  try {
    yield value1
  } catch (error) {
    console.log("捕获到异常情况:", error);
    yield 'abc'
  }

  const value2 = 200
  yield value2

  const value3 = 300
  yield value3
}

const generator = foo()
const result = generator.next() 
console.log(result); // { value: 100, done: false }
if (result.value !== 200) {
  console.log(generator.throw("error message")); // 捕获到异常情况: error message { value: 'abc', done: false }
}
console.log(generator.next()); // { value: 200, done: false }
console.log(generator.next()); // { value: 300, done: false }

6.生成器替代迭代器

因为yield 'abc' 输出 {value: 'abc', done: false},与迭代器的输出结果一样,那么我们可以用生成器替代迭代器,这样的写法更简单

// 生成器替代迭代器
function* createArrayIterator(arr) {
  // 1.第一种方法
  // yield 'abc'
  // yield 'cba'
  // yield 'nba'

  // 2.第二种写法
  // for (const item of arr) {
  //   yield item
  // }

  // 3.第三种写法 yield* 可迭代对象
  yield* arr
}

const names = ["cba", "nba", "abc"]
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());

7.自定义类迭代 – 生成器实现

// 自定义类里的生成器
class Person {
  constructor(address, name, students) {
    this.address = address
    this.name = name
    this.students = students
  }
  entry(newStudent) {
    this.students.push(newStudent)
  }
  *[Symbol.iterator]() {
    yield* this.students
  }
}

const stu = new Person("文科楼301", "计算机教室", ["kobe", "james", "curry", "kk"])
for (const item of stu) {
  console.log(item);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python中,迭代器iterator)是一个对象,它能够被迭代,即能够被用在循环语句中。迭代器必须实现两个方法:\_\_iter\_\_() 和 \_\_next\_\_()。其中,\_\_iter\_\_() 返回迭代器对象本身,\_\_next\_\_() 返回迭代器的下一个值。如果没有更多的值可供返回,那么就应该抛出 StopIteration 异常。 例如,我们可以使用一个迭代器来遍历一个列表: ```python my_list = [1, 2, 3] my_iterator = iter(my_list) print(next(my_iterator)) # 输出 1 print(next(my_iterator)) # 输出 2 print(next(my_iterator)) # 输出 3 ``` 生成器generator)是一种特殊的迭代器,它是通过函数来实现的。生成器函数使用关键字 yield 来返回一个值,而不是使用 return。当函数被调用时,它并不会立即执行,而是返回一个生成器对象。当调用生成器对象的 \_\_next\_\_() 方法时,函数才会执行,并且执行到 yield 关键字时会返回一个值。 例如,下面的代码是一个简单的生成器函数,它生成斐波那契数列: ```python def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b # 使用生成器函数来生成斐波那契数列 f = fibonacci() for i in range(10): print(next(f)) ``` 输出结果为: ``` 0 1 1 2 3 5 8 13 21 34 ``` 在这个例子中,我们定义了一个无限循环的生成器函数 fibonacci(),它每次返回斐波那契数列中的下一个数。我们使用 for 循环来遍历生成器对象 f,并且调用 next(f) 来获取每个数。由于生成器函数是无限循环的,所以我们需要使用 range(10) 来限制循环次数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值