如何使用生成器函数实现循环数组 [英] How do I implement a cycle-through array with a generator function
本文介绍了如何使用生成器函数实现循环数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天,我想知道在TypeScript中提供循环数组的最快方法是什么,如:
Today I was wondering what would be the swiftest method to provide a cycle-through array in TypeScript, as in:
['one', 'two', 'three']
其中,three
之后的下一个值将是one
,我认为这是生成器函数的不错选择.但是,它似乎对我不起作用.以下代码有什么问题?
where the next value after three
would be one
, and I thought that it's a good candidate for a generator function. However it does not seem to work for me. What's wrong with the following code?
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);
推荐答案
您需要在生成器代码中循环,否则只会发生一个yield
:
You need a loop in your generator code, otherwise there is only one yield
happening:
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);
或者,您也可以使用 yield*
从一个可迭代对象中一次一地产生值:
Alternatively you can also use yield*
which yields values from an iterable, one by one:
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);
这篇关于如何使用生成器函数实现循环数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文