【发布时间】: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 < this.props.total; page++)循环可能是最简单的解决方案。无需在此处使用for of循环,即使这相当于 Coffeescript 的for in。 -
...鉴于您将
active设置为最后一个比较,您可以完全省略循环:-) -
等等,什么?你最后的评论让我有点吃惊。
-
我猜你实际上有一个不同的循环体,它不仅仅分配
active变量,但你向我们展示的 sn-p 可以减少到if (this.props.total > 1) active = this.props.total === +this.props.current;
标签: javascript arrays coffeescript ecmascript-6