【问题标题】:Easier way to iterate over generator? [duplicate]迭代生成器的更简单方法? [复制]
【发布时间】:2015-12-02 21:39:08
【问题描述】:

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

在 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)吗?

【问题讨论】:

    标签: javascript c# node.js generator ecmascript-6


    【解决方案1】:

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

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

    使用它:

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

    Documentation

    【讨论】:

    • dang 这是for..of 而不是for..in ...该死的那些习惯。 :)
    • 呃,不。请删除关于 async/await 的那段。这里不需要承诺。
    • @Bergi 你是对的,对不起。这是一个缓慢的星期一,我认为它们是可以互换的。 :)
    • for of 是最好的。我无法理解 Airbnb 是如何负担得起在 eslint 中针对它制定规则的。
    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2015-11-25
    相关资源
    最近更新 更多