此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Iterator.prototype.drop()
Baseline 2025Newly available
Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Iterator 实例的drop() 方法返回一个新的迭代器辅助方法,该迭代器辅助方法会跳过此迭代器的开头的给定数量的元素。
In this article
语法
js
drop(limit)参数
limit要从迭代器的开头丢弃的元素数量。
返回值
一个新的迭代器辅助方法。第一次调用返回的迭代器辅助方法的next() 方法时,当前迭代器立即前进limit 个元素,然后生成下一个元素(即第limit+1 个元素)。然后,迭代器辅助方法会逐一生成剩余元素。如果当前迭代器的元素数量少于limit 个,那么新生成的迭代器辅助方法会在next() 方法第一次调用时立即完成。
异常
示例
>使用 drop()
下面的示例创建一个生成斐波那契数列的迭代器,其丢弃前两个元素,并从第 3 个元素之后的元素开始:
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); // 2console.log(seq.next().value); // 3等价于:
js
const seq = fibonacci();seq.next();seq.next();在 for...of 循环中使用 drop()
当你不想手动快进迭代器时,drop() 是最方便的。因为迭代器也是可迭代的,所以你可以用for...of 循环来迭代返回的辅助方法。
js
for (const n of fibonacci().drop(2)) { console.log(n); if (n > 30) { break; }}// 输出:// 2// 3// 5// 8// 13// 21// 34将 drop() 与 take() 结合使用
你可以将drop() 与Iterator.prototype.take() 结合使用来获取迭代器的切片:
js
for (const n of fibonacci().drop(2).take(5)) { // 丢弃第一个元素,然后取接下来的五个元素 console.log(n);}// 输出:// 2// 3// 5// 8// 13for (const n of fibonacci().take(5).drop(2)) { // 取前五个元素,然后丢弃其中的前两个元素 console.log(n);}// 输出:// 2// 3// 5丢弃元素数量的下限和上限
当limit 为负数或NaN 时,会抛出RangeError 异常:
js
fibonacci().drop(-1); // RangeError: -1 must be positivefibonacci().drop(undefined); // RangeError: undefined must be positive当limit 大于该迭代器可生成的元素总数时(比如Infinity),返回的迭代器辅助方法会立即丢弃所有元素,并在第一次调用next() 时完成。如果当前迭代器是无限的,则返回的迭代器辅助方法永远不会完成。
js
fibonacci().drop(Infinity).next(); // 永远不会结束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 }规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-iterator.prototype.drop> |