类似于问题Convert ES6 Iterable to Array的东西.但我只想要前N个项目.我有没有内置这样做?或者我怎样才能更优雅地实现这一目标?
let N = 100;
function *Z() { for (let i = 0; ; i++) yield i; }
// This wont work
// Array.from(Z()).slice(0, N);
// [...Z()].slice(0, N)
// This works, but a built-in may be preferred
let a = [], t = Z(); for (let i = 0; i < N; i++) a.push(t.next().value);
解决方法:
要获取迭代器的前n个值,可以使用以下之一:
Array.from({length: n}, function(){ return this.next().value; }, iterator);
Array.from({length: n}, (i => () => i.next().value)(iterator));
要获取任意迭代的迭代器,请使用:
const iterator = iterable[Symbol.iterator]();
在你的情况下,给定一个生成器函数Z:
Array.from({length: 3}, function(){ return this.next().value; }, Z());
如果您更频繁地需要此功能,则可以创建生成器函数:
function* take(iterable, length) {
const iterator = iterable[Symbol.iterator]();
while (length-- > 0) yield iterator.next().value;
}
// Example:
const set = new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
console.log(...take(set, 3));