我对生成器函数比较陌生,想知道是否有办法获取生成器函数生成的先前值。我知道我可以使用 .next()
继续执行下一个 yield
,但我想知道是否可以执行类似 .prev( )
,这实际上会后退一步。
我希望 .prev()
能起作用,但不幸的是它不起作用:
const array = ['a', 'b', 'c'];
function* f(array) {
let i = 0;
while(true) {
yield array[i];
i = (i+1) % array.length;
}
}
const seq = f(array);
console.log(seq.next().value); // a
console.log(seq.next().value); // b
console.log(seq.next().value); // c
console.log(seq.next().value); // a
// console.log(seq.prev().value); // c <-- expect 'c'
正如我所提到的,我对生成器缺乏经验,如果有更好的数据结构/方法来逐步获取值(上一个和下一个),我愿意听取这些建议
最佳答案
您可以让生成器检查 yield
的结果,如果它是某个表达式(如 'prev'
),则递减 i
> 而不是增加它:
const array = ['a', 'b', 'c'];
function* f(array) {
let i = 0;
while (true) {
const incOrDec = (yield array[i]) === 'prev' ? -1 : 1;
i = (array.length + i + incOrDec) % array.length;
}
}
const seq = f(array);
console.log(seq.next().value); // a
console.log(seq.next().value); // b
console.log(seq.next().value); // c
console.log(seq.next().value); // a
console.log(seq.next('prev').value); // c <-- expect 'c'
如果您没有将功能构建到生成器中,则必须将上一次迭代的结果显式保存在变量中,然后检查它。没有像 .prev
这样的内置方法。
I'm inexperienced with generators, and if there is a better data-structure/method to progressively get values (previous and next) I'm open to hearing about those suggestions
如果您不需要使用生成器,并且您的目的是能够向前和向后迭代,那么就不要使用。如果您从一个生成器开始(就像您无法控制的外部函数),那么您可以使用类似于上面的方法将生成器转换为可以向前和向后导航的生成器。否则,只需使用一个普通数组,将值放入其中并查找索引,例如:
const array = ['a', 'b', 'c'];
function* f(array) {
let i = 0;
while (true) {
const incOrDec = (yield array[i]) === 'prev' ? -1 : 1;
i = (array.length + i + incOrDec) % array.length;
}
}
const cache = [];
const getValue = i => cache[i] || (cache[i] = /* put logic for retrieving value here */ array[i % array.length]);
console.log(getValue(0));
console.log(getValue(1));
console.log(getValue(2));
console.log(getValue(3));
console.log(getValue(4));
console.log(getValue(3));
关于javascript - 从生成器函数获取先前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142867/