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


当前回答

我做了这个:

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数量的图像,这很有用。

其他回答

我做了这个:

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数量的图像,这很有用。

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,控制台

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

在函数式范式中,重复通常是一个无限递归函数。要使用它,我们需要惰性求值或延续传递样式。

惰性求值函数重复

const重复= f = > x = > [x,() = >重复(f) (f (x))); Const take = n => ([x, f]) => n === 0 ?X:取(n - 1) (f()); console.log ( 取(8)(repeat(x => x * 2) (1)) // 256 );

我使用一个thunk(一个没有参数的函数)来实现Javascript中的惰性求值。

延续传递样式的函数重复

const重复= f = > x = > [x, k = > k(重复(f) (f (x)))); Const take = n => ([x, k]) => n == 0 ?X: k(取(n - 1)); console.log ( 取(8)(repeat(x => x * 2) (1)) // 256 );

CPS一开始有点吓人。然而,它总是遵循相同的模式:最后一个参数是continuation(一个函数),它调用自己的主体:k => k(…)。请注意CPS将应用程序翻过来,即take(8)(重复…)变成k(take(8))(…)其中k是部分应用的重复。

结论

通过将重复(repeat)与终止条件(take)分离,我们获得了灵活性——将关注点分离到痛苦的尽头:D