如何使用生成器函数实现循环数组

时间:2016-12-30 23:56:48

标签: javascript typescript generator yield

今天我想知道在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);

1 个答案:

答案 0 :(得分:6)

您需要在生成器代码中使用循环,否则只会发生一个yield

&#13;
&#13;
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;
&#13;
&#13;

或者你也可以使用yield*从一个可迭代的值中逐个产生值:

&#13;
&#13;
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;
&#13;
&#13;