最佳答案
这里有一种在 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]
使用普通的 JavaScript,我们能做的最接近的事情是什么?
我知道像 Underscore 这样的库,但是这里我尽量避免使用库。
我看了 重复一个字符串多次的答案,但它不适用于一般情况。例如:
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
其他几个答案建议修改内置类; 我认为这种做法是完全不可接受的。