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


当前回答

Afaik,在ES6中没有类似Ruby的times方法的机制。但是你可以通过使用递归来避免突变:

let times = (i, cb, l = i) => {
  if (i === 0) return;

  cb(l - i);
  times(i - 1, cb, l);
}

times(5, i => doStuff(i));

演示:http://jsbin.com/koyecovano/1/edit?js,控制台

其他回答

此解决方案的优点

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

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

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

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

使用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'))

我用一个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']