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

标签 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);

最佳答案

您的生成器代码中需要一个循环,否则只会发生一个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);

或者你也可以使用 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);

关于javascript - 如何使用生成器函数实现循环数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404182/

相关文章:

javascript - 如何使第一个数组成为标题和剩余数组行的对象

javascript - TypeScript 错误对象原型(prototype)只能是对象或 null : undefined

javascript - 如何用JS复制字符串中的每个字母

javascript - 查询检查在哪里

javascript - Bootstrap 下拉菜单仅适用于主页(Joomla 3.0)

javascript - 在 typescript 中调用不同实例的数组元素的方法?

javascript - 如何从 localStorage Angular 中的数组中删除单个对象

Python 仅在 for 循环未开始迭代(使用生成器)时才执行代码?

python - 为什么将生成器传递给 iter 来使用它的生成器函数?

python - 具有多个输入层的 Keras fit_generator