成语为“重复n次”? [英] Idiom for "repeat n times"?

查看:92
本文介绍了成语为“重复n次”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:要关闭的投票是错误的。 重复字符N次中接受的答案通常不适用。例如:

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

>>> Array(3).map(Math.random)
[undefined, undefined, undefined]

另外两个答案建议修改内置类,我认为这种做法完全不可接受。

The other two answers propose modifying a built-in class, a practice that I consider completely unacceptable.

这里有一个在JS中生成3个随机数的数组的浪费和不切实际的方法:

Here's one somewhat wasteful and impractical way to produce an array of 3 random numbers in JS:

>>> [1, 1, 1].map(Math.random)
[0.6324464592887568, 0.5969209806782131, 0.7362755801487572]

使用虚拟数组(例如 [1,1,1] ),以便可以调用 map 就此而言,是因为足够大的 n 既浪费(内存)也不实用。

The use of a dummy array (e.g. [1, 1, 1]) just so that one can call map on it, is, for sufficiently large n both wasteful (of memory) and impractical.

人们想要的是什么?像一个假设:

What one would like would be something like a hypothetical:

>>> repeat(3, Math.random)
[0.21425955396598173, 0.00226050232425945, 0.45261888146445495]

什么是最接近的人可以在纯JS中找到它吗?

What's the closest one can come to this in "pure JS"?

(我知道Underscore,但是它的API中的东西对我来说没有意义,比如解释 map ,所以我试图避免它。)

(I'm aware of Underscore, but there's stuff in its API that makes no sense to me, such as interpretation of map, so I'm trying to avoid it.)

推荐答案

Underscore.js有一个功能,可以完全满足您的需求:

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

_.times(3, Math.random)

如果您不想使用Underscore,您可以编写自己的函数(从Underscore源复制并略微简化):

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;
};

这篇关于成语为“重复n次”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆