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

瀏覽器相容性

另見