【问题标题】:Turn Coffeescript loop using range into ES6将使用范围的 Coffeescript 循环转换为 ES6
【发布时间】:2017-02-08 23:00:31
【问题描述】:

免责声明:我不知道 Coffeescript,虽然我很欣赏它对 ES6 规范的贡献,但我迫不及待地想看到它的背面。

这个 Coffeescript 循环(别人写的)

if @props.total>1
  for page in [1..@props.total]
    active = (page is +@props.current)

是,根据js2coffee,相当于这个JS

var active, i, page, ref;

if (this.props.total > 1) {
  for (page = i = 1, ref = this.props.total; 1 <= ref ? i <= ref : i >= ref; page = 1 <= ref ? ++i : --i) {
    active = page === +this.props.current;
  }
}

现在我想使用for..of 循环来缩短该JS,但我不知道如何。

我尝试实现this idea(底部的生成器功能位),但我无法正确完成。

我的问题是:有没有办法在 ES6 中创建范围?

【问题讨论】:

  • 链接文章中的function* range 应该可以工作(不,没有很多其他方法可以实现范围)。请向我们展示您尝试过的确切代码。
  • 一个简单的for (let page = 1; page &lt; this.props.total; page++) 循环可能是最简单的解决方案。无需在此处使用 for of 循环,即使这相当于 Coffeescript 的 for in
  • ...鉴于您将active 设置为最后一个比较,您可以完全省略循环:-)
  • 等等,什么?你最后的评论让我有点吃惊。
  • 我猜你实际上有一个不同的循环体,它不仅仅分配 active 变量,但你向我们展示的 sn-p 可以减少到 if (this.props.total &gt; 1) active = this.props.total === +this.props.current;

标签: javascript arrays coffeescript ecmascript-6


【解决方案1】:

为了在 JavaScript 中从 n 开始生成长度为 k 的任意范围的连续整数,以下应该可以工作:

Array.apply(null, Array(k)).map((x, i) => i + n);

虽然与coffeescript range 功能相当相同,但对于大多数用途来说,它可能已经足够接近了。此外,尽管更加冗长,但它有一个明显的优势:您不必记住 ..... 中的哪一个是专有的,哪个是包容性的。

【讨论】:

    【解决方案2】:

    您正在寻找的生成器解决方案是

    function* range(i, end=Infinity) {
        while (i <= end) {
            yield i++;
        }
    }
    
    // if (this.props.total > 1) - implicitly done by `range`
    for (let page of range(1, this.props.total) {
        active = page === +this.props.current;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2019-03-07
      • 2021-03-07
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多