Iterating with while loop instead of for loop

Randomblue提出了一个问题:Iterating with while loop instead of for loop,或许与您遇到的问题类似。

回答者fsw给出了该问题的处理方式:

Would something like this satisfy you?

var sequence = fibonacci();
var value;
while ((value = sequence.next()) < 1000) {
    console.log(value);
}

plus, maybe even a nicer solution would be something like:

function* fibonacci(limit){
  let previous = 0;
  let current = 1;

  while(previous + current < limit) {
    let temp = previous;
    previous = current;
    yield current = temp + current;
  }
}

for(let value of fibonacci(1000)) {
    console.log(value);
}

希望本文对你有帮助,欢迎支持JavaScript中文网