Idiom for “repeat n times”?

后端 未结 6 2192
忘掉有多难
忘掉有多难 2020-12-15 02:24

EDIT: The votes to close are wrong. The accepted answer in Repeat Character N Times is not applicable in general. E.g.:

>>>         


        
6条回答
  •  生来不讨喜
    2020-12-15 02:56

    Underscore.js has a times function that does exactly what you want:

    _.times(3, Math.random)
    

    If you don't want to use Underscore, you can just write your own times function (copied and slightly simplified from the Underscore source):

    times = function(n, iterator) {
      var accum = Array(Math.max(0, n));
      for (var i = 0; i < n; i++) accum[i] = iterator.call();
      return accum;
    };
    

提交回复
热议问题