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


当前回答

使用ES2015 Spread操作符:

[...阵列(n)](文件夹)。

const res = [...Array(10)].map((_, i) => {
  return i * 10;
});

// as a one liner
const res = [...Array(10)].map((_, i) => i * 10);

或者如果你不需要结果:

[...Array(10)].forEach((_, i) => {
  console.log(i);
});

// as a one liner
[...Array(10)].forEach((_, i) => console.log(i));

或者使用ES2015 Array.from操作符:

Array.from(…)

const res = Array.from(Array(10)).map((_, i) => {
  return i * 10;
});

// as a one liner
const res = Array.from(Array(10)).map((_, i) => i * 10);

注意,如果你只是需要重复一个字符串,你可以使用string .prototype.repeat。

console.log("0".repeat(10))
// 0000000000

其他回答

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

使用ES2015 Spread操作符:

[...阵列(n)](文件夹)。

const res = [...Array(10)].map((_, i) => {
  return i * 10;
});

// as a one liner
const res = [...Array(10)].map((_, i) => i * 10);

或者如果你不需要结果:

[...Array(10)].forEach((_, i) => {
  console.log(i);
});

// as a one liner
[...Array(10)].forEach((_, i) => console.log(i));

或者使用ES2015 Array.from操作符:

Array.from(…)

const res = Array.from(Array(10)).map((_, i) => {
  return i * 10;
});

// as a one liner
const res = Array.from(Array(10)).map((_, i) => i * 10);

注意,如果你只是需要重复一个字符串,你可以使用string .prototype.repeat。

console.log("0".repeat(10))
// 0000000000

发电机吗?递归?为什么这么讨厌突变?: -)

如果它是可以接受的,只要我们“隐藏”它,那么只要接受一元操作符的使用,我们就可以让事情变得简单:

Number.prototype.times = function(f) { let n=0 ; while(this.valueOf() > n) f(n++) }

就像在ruby中:

> (3).times(console.log)
0
1
2

我来晚了,但由于这个问题经常出现在搜索结果中,我只想添加一个解决方案,我认为它在可读性方面是最好的,同时不长(这对于任何代码库都是理想的)。它会变异,但我愿意为KISS原则做出妥协。

let times = 5
while( times-- )
    console.log(times)
// logs 4, 3, 2, 1, 0

下面是另一个不错的选择:

Array.from({ length: 3}).map(...);

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

Array.from({ length: 3 }, () => (...))