Javascript 如何实现 enumerate 函数

Ivan Lv6

Javascript 实现 enumerate 函数

1
2
3
4
5
6
7
function* enumerate(iterator, start = 0) {
let index = start;
for (const item of iterator) {
yield [index, item];
index++;
}
}

function* 是生成器语法, 用于惰性生成. 关键字 yield 可以返回结果.

一个生成器可以通过调用 next() 方法获得数据, 使用返回对象中 done 属性判断是否消费完毕.

1
2
3
4
5
while (true) {
let {value, done} = iter.next();
if (done) break;
// ... process value
}

调用 next() 方法会返回一个对象, 其中包含两个属性 value 以及 done.

  • Title: Javascript 如何实现 enumerate 函数
  • Author: Ivan
  • Created at : 2026-06-21 00:00:00
  • Updated at : 2026-10-23 18:02:31
  • Link: https://ivanfan-van.github.io/2026/06/21/note-4-evergreen-007/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Javascript 如何实现 enumerate 函数