成语为“重复n次”?

编程入门 行业动态 更新时间:2024-10-25 03:25:19
本文介绍了成语为“重复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次”?

本文发布于:2023-11-30 20:19:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651362.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成语

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!