Iterator.prototype.drop()
drop() 方法是 Iterator 例項的一個方法,它返回一個新的 iterator helper object,該物件會跳過此迭代器開頭的指定數量的元素。
語法
js
drop(limit)
引數
limit-
要從迭代開頭跳過的元素數量。
返回值
一個新的 iterator helper object。返回的 iterator helper 的 next() 方法首次被呼叫時,當前迭代器會立即前進 limit 個元素,然後產生第 limit+1 個元素。之後,iterator helper 會逐個產生剩餘的元素。如果當前迭代器的元素少於 limit 個,那麼在首次呼叫 next() 時,新的 iterator helper 將會立即完成。
異常
示例
使用 drop()
下面的例子建立了一個迭代器,該迭代器產生斐波那契數列的項,透過跳過前兩項來從第三項開始。
js
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
const seq = fibonacci().drop(2);
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
這等價於
js
const seq = fibonacci();
seq.next();
seq.next();
將 drop() 與 for...of 迴圈一起使用
drop() 在您不手動編寫迭代器時最為方便。因為迭代器也是可迭代的,所以您可以使用 for...of 迴圈來迭代返回的 helper。
js
for (const n of fibonacci().drop(2)) {
console.log(n);
if (n > 30) {
break;
}
}
// Logs:
// 2
// 3
// 5
// 8
// 13
// 21
// 34
將 drop() 與 take() 結合使用
您可以將 drop() 與 Iterator.prototype.take() 結合使用來獲取迭代器的切片。
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
drop 計數的上下限
當 limit 為負數或 NaN 時,將丟擲 RangeError。
js
fibonacci().drop(-1); // RangeError: -1 must be positive
fibonacci().drop(undefined); // RangeError: undefined must be positive
當 limit 大於迭代器能產生的總元素數量(例如 Infinity)時,返回的 iterator helper 將會立即跳過所有元素,並在首次呼叫 next() 時完成。如果當前迭代器是無限的,那麼返回的 iterator helper 將永遠不會完成。
js
fibonacci().drop(Infinity).next(); // Never ends
new Set([1, 2, 3]).values().drop(Infinity).next(); // { value: undefined, done: true }
new Set([1, 2, 3]).values().drop(4).next(); // { value: undefined, done: true }
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-iterator.prototype.drop |
瀏覽器相容性
載入中…