本文介绍了如何迭代发生器函数的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来迭代发生器的结果,我的for循环是丑陋的:

  for(let job = readyJob.next();!job.done; job = readyJob.next()){} 

在上下文中有一个生成函数可以确定是否有一批工作,由1 .. *作业组成(生成器也可能不返回批处理中的作业)。有一个连续的循环来实例化生成器,并在批处理中进行重复操作(日志记录)。



这个迭代问题有一个更优雅的解决方案。我的意思是这看起来像Java / C#的传统迭代器,这不错。像每个这样的东西将是超级可读的...这是我的希望无论如何。

  let getReadyJob = function *(instance) {
let numJobs = 7; // getRandomInt(0,10);
for(let i = 0; i< numJobs; i ++){
yield {
jobId:''+ instance +'::'+ i,
jobReadyOn new Date())。valueOf()
};
}
}

然后


$ b $($)$($)$($)$($)$($)$ {
let readyJob = getReadyJob()

for(let job = readyJob.next .done; job = readyJob.next()){
console.log(JSON.stringify(job.value));
}
}


解决方案

是如果您的环境已经支持的

  for(var job of readyJob){
// ...
}

如果没有,看过这几次:

  var next; 
while(!(next = readyJob.next())。done){
var job = next.value;
// ...
}


Is there a better way to iterate over the results of a generator, my for loop is ugly:

for(let job = readyJob.next(); !job.done; job = readyJob.next()){ } 

In context there is a generator function that can determine if there is a batch of work, consisting of 1..* jobs (the generator may also return no jobs in the batch). There is a continuous loop that instantiates the generator and iterates over the batch doing work on the job (logging).

Is there a more elegant solution to this iteration problem. I mean this looks like a traditional iterator from Java/C# which isn't bad. Something like an "each" would be super readable... That's my hope anyhow.

 let getReadyJob = function *(instance){
    let numJobs = 7 ; // getRandomInt(0, 10) ;
    for(let i = 0; i < numJobs; i++) {
        yield {
            jobId: '' + instance + '::' + i,
            jobReadyOn: (new Date()).valueOf()
        };
    }
}

then

while(true){
    let readyJob = getReadyJob()

    for(let job = readyJob.next(); !job.done; job = readyJob.next()){
        console.log(JSON.stringify(job.value)) ;
    }
}
解决方案

Yes, if your environment already supports for...of:

for (var job of readyJob) {
  // ...
}

If not, have seen this a couple of times:

var next;
while (!(next = readyJob.next()).done) {
   var job = next.value;
   // ...
}

这篇关于如何迭代发生器函数的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:26