这是在 JS 中生成 3 个随机数数组的一种有点浪费且不切实际的方法:
[1, 1, 1].map(Math.random) // Outputs: [0.63244645928, 0.59692098067, 0.73627558014]
使用虚拟数组(例如 [1, 1, 1]
),只是为了可以调用 map
在它上面,对于足够大的 n - 既浪费(内存)又不切实际.
人们想要什么,就像一个假设:
repeat(3, Math.random) // Outputs: [0.214259553965, 0.002260502324, 0.452618881464]
使用 vanilla JavaScript 我们最接近的是什么?
我知道像 Underscore 这样的库,但我尽量避免使用这里的库。
我看了 Repeat a string a number of times 的答案,但一般情况下不适用。例如:
Array(3).map(Math.random) // Outputs: [undefined, undefined, undefined]
Array(4).join(Math.random()) // Outputs a concatenation of a repeated number
Array(3).fill(Math.random()) // Fills with the same number
其他几个答案建议修改内置类;我认为这是完全不能接受的做法。
原文由 kjo 发布,翻译遵循 CC BY-SA 4.0 许可协议
Underscore.js 有一个 times 函数,可以完全满足您的需求:
如果您不想使用 Underscore,您可以编写自己的
times
函数(从 Underscore 源代码复制并稍微简化):