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 |
浏览器兼容性
加载中…