在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中有更好的机制。


当前回答

Array(100).fill().map((_,i)=> console.log(i) );

这个版本满足了OP对不变性的要求。还要根据您的用例考虑使用reduce而不是map。

这也是一个选择,如果你不介意在你的原型中做一点改变的话。

Number.prototype.times = function(f) {
   return Array(this.valueOf()).fill().map((_,i)=>f(i));
};

现在我们可以这么做了

((3).times(i=>console.log(i)));

+1到arcseldon的.fill建议。

其他回答

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

我用一个helper函数包装了@Tieme的答案。

在打字稿:

export const mapN = <T = any[]>(count: number, fn: (...args: any[]) => T): T[] => [...Array(count)].map((_, i) => fn())

现在你可以运行:

const arr: string[] = mapN(3, () => 'something')
// returns ['something', 'something', 'something']

我做了这个:

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.from({ length: 3}).map(...);

最好,就像@Dave Morse在评论中指出的那样,你也可以通过使用Array.from函数的第二个参数来摆脱map调用,就像这样:

Array.from({ length: 3 }, () => (...))
const times = 4;
new Array(times).fill().map(() => console.log('test'));

这段代码将console.log测试4次。