在JavaScript中循环x次的典型方法是:

for (var i = 0; i < x; i++)
  doStuff(i);

但我不想使用++运算符或任何可变变量。那么在ES6中,是否有一种方法来循环x乘以另一种方法?我喜欢Ruby的机制:

x.times do |i|
  do_stuff(i)
end

JavaScript/ES6中有类似的吗?我可以欺骗自己的生成器:

function* times(x) {
  for (var i = 0; i < x; i++)
    yield i;
}

for (var i of times(5)) {
  console.log(i);
}

当然,我仍然在使用i++。至少它在视线之外:),但我希望在ES6中有更好的机制。


当前回答

对我来说,这是许多级别的开发人员最容易理解的答案 Const times = (n, callback) => { 而(n) { 回调(); n——; } } Times (10, ()=> console.log('hello'))

其他回答

这是我能想到的在range内创建列表/数组的最简单的方法

Array.from(Array(max-min+1), (_, index) => index+min)

我做了这个:

function repeat(func, times) {
    for (var i=0; i<times; i++) {
        func(i);
    }
}

用法:

repeat(function(i) {
    console.log("Hello, World! - "+i);
}, 5)

/*
Returns:
Hello, World! - 0
Hello, World! - 1
Hello, World! - 2
Hello, World! - 3
Hello, World! - 4
*/

变量i返回它循环的次数-如果你需要预加载x数量的图像,这很有用。

我还有另一个选择

[...Array(30).keys()]

对我来说,这是许多级别的开发人员最容易理解的答案 Const times = (n, callback) => { 而(n) { 回调(); n——; } } Times (10, ()=> console.log('hello'))

我认为这很简单:

[...Array(3).keys()]

or

Array(3).fill()