【问题标题】:How do I implement a cycle-through array with a generator function如何使用生成器函数实现循环数组
【发布时间】:2017-05-15 05:22:16
【问题描述】:

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

【问题讨论】:

  • 你需要在你的生成器代码中有一个循环。

标签: javascript typescript generator yield


【解决方案1】:

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

【讨论】:

  • 另外,如果你把数组作为参数,它是一个立即可用的 OP 块
  • @BalázsÉdes,谢谢,我采纳了这个改进想法。
  • 没错,@BalázsÉdes 是对的——我也在发现新事物的力量,比如 Map、Set 或 generator。不太确定我是否需要一个生成器,但使用可能的语法,这只是一个梦想。不过想知道,为什么 jsfiddle.net 在尝试在 JavaScript 1.7 或 TypeScript 下运行此代码时会吐出错误。不得不求助于小提琴中的常规 JavaScript 选项。
  • 似乎可以和Javascript 1.7一起使用,但是jsfiddle中的TypeScript版本不支持yield。我想它不是 1.6 版。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多