将Coffeescript循环使用范围转换为ES6 [英] Turn Coffeescript loop using range into ES6
问题描述
免责声明:我不知道Coffeescript,虽然我感谢它对ES6规格做出了贡献,但我迫不及待地看到了它。
Disclaimer: I don't know Coffeescript and, although I appreciate it has contributed towards the ES6 spec, I can't wait to see the back it.
这个Coffeescript循环(由别人写)
This Coffeescript loop (wrote by someone else)
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,但我无法弄清楚如何。
Now I would like to use a for..of
loop to shorten that JS, but I can't figure out how.
我试图实现<一个href =http://davidarvelo.com/blog/array-number-range-sequences-in-javascript-es6/ =nofollow>这个想法(底部的生成函数位)但是我不能正确的。
I've tried to implement this idea(the generator function bit at the bottom), but I can't get it right.
我的问题是:有没有办法在ES6中制作范围?
My question is: Is there a way of making ranges in ES6?
推荐答案
您正在寻找的生成器解决方案是
The generator solution you are looking for would be
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;
}
这篇关于将Coffeescript循环使用范围转换为ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!