今天我想知道在TypeScript中提供循环数组的最快方法是什么,如:
['one', 'two', 'three']
three
之后的下一个值是one
,我认为它是生成器函数的一个很好的候选者。但它似乎对我不起作用。以下代码有什么问题?
function* stepGen(){
const steps = ['one', 'two', 'three'];
let index = 0;
if(index < steps.length - 1){
index++;
} else {
index = 0;
}
yield steps[index];
}
let gen = stepGen();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value); // should be 'three'
console.log(gen.next().value); // should be 'one'
console.log(gen.next().value);
答案 0 :(得分:6)
您需要在生成器代码中使用循环,否则只会发生一个yield
:
function* stepGen(steps){
let index = 0;
while (true) {
yield steps[index];
index = (index+1)%steps.length;
}
}
let gen = stepGen(['one', 'two', 'three']); // pass array to make it more reusable
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
&#13;
或者你也可以使用yield*
从一个可迭代的值中逐个产生值:
function* stepGen(steps){
while (true) yield* steps;
}
let gen = stepGen(['one', 'two', 'three']);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
&#13;