如何获取生成器的第 n 个值?
function *index() {
let x = 0;
while(true)
yield x++;
}
// the 1st value
let a = index();
console.log(a.next().value); // 0
// the 3rd value
let b = index();
b.next();
b.next();
console.log(b.next().value); // 2
// the nth value?
let c = index();
let n = 10;
console.log(...); // 9
最佳答案
你可以定义一个像in python这样的枚举方法:
function *enumerate(it, start) {
start = start || 0;
for(let x of it)
yield [start++, x];
}
然后:
for(let [n, x] of enumerate(index()))
if(n == 6) {
console.log(x);
break;
}
http://www.es6fiddle.net/ia0rkxut/
沿着同样的思路,也可以重新实现 pythonic range
和 islice
:
function *range(start, stop, step) {
while(start < stop) {
yield start;
start += step;
}
}
function *islice(it, start, stop, step) {
let r = range(start || 0, stop || Number.MAX_SAFE_INTEGER, step || 1);
let i = r.next().value;
for(var [n, x] of enumerate(it)) {
if(n === i) {
yield x;
i = r.next().value;
}
}
}
然后:
console.log(islice(index(), 6, 7).next().value);
http://www.es6fiddle.net/ia0s6amd/
现实世界的实现需要更多的工作,但您明白了。
关于javascript - 如何获取 JavaScript 生成器的第 n 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410359/