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

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

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

其他回答

处理功能方面:

function times(n, f) {
    var _f = function (f) {
        var i;
        for (i = 0; i < n; i++) {
            f(i);
        }
    };
    return typeof f === 'function' && _f(f) || _f;
}
times(6)(function (v) {
    console.log('in parts: ' + v);
});
times(6, function (v) {
    console.log('complete: ' + v);
});

此解决方案的优点

最容易阅读/使用(我觉得) 返回值可以用作和,也可以忽略 普通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

我把它放在这里。如果你正在寻找一个不使用数组的紧凑函数,并且你对可变性/不可变性没有问题:

var g =x=>{/*your code goes here*/x-1>0?g(x-1):null};
 

我做了这个:

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 }, () => (...))