更简单的方法来迭代生成器

Easier way to iterate over generator?

本文关键字:迭代 方法 更简单      更新时间:2023-09-26

是否有一种更简单的方法(比我使用的)来迭代生成器?某种最佳实践模式或通用包装器?

在c#中,我通常会有这样简单的东西:

public class Program {
    private static IEnumerable<int> numbers(int max) {
        int n = 0;
        while (n < max) {
            yield return n++;
        }
    }
    public static void Main() {
        foreach (var n in numbers(10)) {
            Console.WriteLine(n);
        }
    }
}

在JavaScript中尝试同样的方法,这是我能想到的最好的:

function* numbers(max) {
  var n = 0;
  while (n < max) {
    yield n++;
  }
}
var n;
var numbers = numbers(10);
while (!(n = numbers.next()).done) {
  console.log(n.value);
}

虽然我期望的是这样简单的事情…

function* numbers(max) {
  let n = 0;
  while (counter < max) {
    yield n++;
  }
}
for (let n in numbers(10)) {
  console.log(n);
}

…哪个更容易读,更简洁,但显然还没有那么简单?我尝试过node 0.12.7--harmony标志和node 4.0.0 rc1。如果这个功能可用,我还需要做些什么来启用这个功能(包括使用let)吗?

您需要为生成器使用for..of语法。这将为可迭代对象创建一个循环。

function* numbers(max) {
  let n = 0;
  while (n < max) {
    yield n++;
  }
}
使用它:

for (let n of numbers(10)) {
  console.log(n); //0123456789
}
文档