在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

其他回答

此解决方案的优点

最容易阅读/使用(我觉得) 返回值可以用作和,也可以忽略 普通es6版本,也链接到TypeScript版本的代码

缺点 ——突变。只是内在我不在乎,也许其他人也不在乎。

示例和代码

times(5, 3)                       // 15    (3+3+3+3+3)

times(5, (i) => Math.pow(2,i) )   // 31    (1+2+4+8+16)

times(5, '<br/>')                 // <br/><br/><br/><br/><br/>

times(3, (i, count) => {          // name[0], name[1], name[2]
    let n = 'name[' + i + ']'
    if (i < count-1)
        n += ', '
    return n
})

function times(count, callbackOrScalar) {
    let type = typeof callbackOrScalar
    let sum
    if (type === 'number') sum = 0
    else if (type === 'string') sum = ''

    for (let j = 0; j < count; j++) {
        if (type === 'function') {
            const callback = callbackOrScalar
            const result = callback(j, count)
            if (typeof result === 'number' || typeof result === 'string')
                sum = sum === undefined ? result : sum + result
        }
        else if (type === 'number' || type === 'string') {
            const scalar = callbackOrScalar
            sum = sum === undefined ? scalar : sum + scalar
        }
    }
    return sum
}

TypeScipt版本 https://codepen.io/whitneyland/pen/aVjaaE?editors=0011

const times = 4;
new Array(times).fill().map(() => console.log('test'));

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

在我看来,这个问题最正确的答案(这是有争议的)隐藏在Sasha Kondrashov的评论中,也是最简洁的,只用了两个字:“不”。没有比Ruby的语法更好的for循环替代函数了。我们可能希望有一个,但就是没有。

问题中没有明确说明,但我认为任何“循环N次”问题的解决方案都不应该分配内存,至少不与N成正比。这个标准将排除大多数“原生javascript”的答案。

其他答案显示了Ruby中的实现,这很好,除了这个问题显式地要求本机javascript解决方案。这个问题已经有了一个非常不错的手卷解决方案,可以说是最易读的解决方案之一。

我还有另一个选择

[...Array(30).keys()]
for (let i of Array(100).keys()) {
    console.log(i)
}