Iterator.prototype.take()

基准线 2025
新推出

自 ⁨2025 年 3 月⁩ 起,此功能可在最新的设备和浏览器版本上使用。此功能可能在旧设备或浏览器上无法正常工作。

take() 方法是 Iterator 实例的一个方法,它返回一个新的 迭代器辅助对象,该对象会生成指定数量的元素,然后终止。

语法

js
take(limit)

参数

limit

从迭代开始要取的元素数量。

返回值

一个新的 迭代器辅助对象。返回的迭代器辅助对象将逐个生成原始迭代器中的元素,并在生成 limit 个元素后完成(此时 next() 方法返回 { value: undefined, done: true }),或者在原始迭代器耗尽时完成,以先发生的为准。

异常

RangeError

如果 limit转换为整数后变成 NaN 或负数,则会抛出错误。

示例

使用 take()

下面的示例创建了一个生成斐波那契数列项的迭代器,然后打印出前三项。

js
function* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci().take(3);
console.log(seq.next().value); // 1
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // undefined

将 take() 与 for...of 循环一起使用

take() 在你不需要手动处理迭代器时最为方便。因为迭代器本身也是可迭代的,你可以使用 for...of 循环来迭代返回的辅助对象。

js
for (const n of fibonacci().take(5)) {
  console.log(n);
}

// Logs:
// 1
// 1
// 2
// 3
// 5

由于 fibonacci() 是一个无限迭代器,如果使用 for 循环遍历它而没有任何提前退出的逻辑(例如 break 语句),将会导致无限循环。

将 drop() 与 take() 结合使用

你可以将 take()Iterator.prototype.drop() 结合使用,以获取迭代器的切片。

js
for (const n of fibonacci().drop(2).take(5)) {
  // Drops the first two elements, then takes the next five
  console.log(n);
}
// Logs:
// 2
// 3
// 5
// 8
// 13

for (const n of fibonacci().take(5).drop(2)) {
  // Takes the first five elements, then drops the first two
  console.log(n);
}
// Logs:
// 2
// 3
// 5

take 计数的下限和上限

limit 为负数或 NaN 时,会抛出 RangeError

js
fibonacci().take(-1); // RangeError: -1 must be positive
fibonacci().take(undefined); // RangeError: undefined must be positive

limit 大于迭代器可以产生的总元素数量(例如 Infinity)时,返回的迭代器辅助对象的行为基本上与原始迭代器相同。

js
for (const n of new Set([1, 2, 3]).values().take(Infinity)) {
  console.log(n);
}

// Logs:
// 1
// 2
// 3

规范

规范
ECMAScript® 2026 语言规范
# sec-iterator.prototype.take

浏览器兼容性

另见