Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

[1, 1, 1].map(Math.random) // Outputs: [0.63244645928, 0.59692098067, 0.73627558014]

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) // Outputs: [0.214259553965, 0.002260502324, 0.452618881464]

What's the closest we can do using vanilla JavaScript?

I'm aware of libraries like Underscore, but I'm trying to avoid libraries here.

I looked at the answers to Repeat a string a number of times, but it is not applicable in general. E.g.:

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

Several other answers propose modifying a built-in class; a practice that I consider completely unacceptable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

It can be done using Array.prototype.map, but the array can't be empty. Fill it first:

console.log(
    Array(3).fill().map(Math.random)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...