以下是一种在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
有几个答案建议修改内置类,但我认为这完全不可接受。
[1,1,1].map(Math.random)
,因为它是浪费的。那么Array(3).map(Math.random)
有什么不同呢?当然,我知道对于n=3,浪费是微不足道的,但对于更大的n则不是这样。 - kjoArray(100)
比[1, 2, 3, 4, 5, 6, 7, ... 100]
要简洁得多。至于你所说的“浪费”,我不明白问题在哪里。你认为有一种神奇的方法可以做到你想要的,而又不需要分配一个数组吗? - Chris Laplantevar n = 5; alert(String(Array(n+1)).split('').map(Math.random));
。 现在请原谅我,我需要用 JSON 清洗我的口腔。 - sgbj