Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - Idiom for "repeat n times"?

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

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

1 Reply

0 votes
by (71.8m points)

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)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...