Following up on this answer for creating an array of specified length, I executed the below to get a corresponding result but filled with random numbers, instead of zeros.
var randoms = Array(4).fill(Math.floor(Math.random() * 9));
Well, mathematically speaking it's random, all right. But I'd like the randomness to be visible within the array and not only between runs, of course. Stupid computer... Don't do what I say. Do what I want!
I can iterate and put it my random (and varying) values. But I wonder, of pure curiosity, if it's possible to get the right result with a one-liner, like above, MatLab-style. Do I need to call eval(function()...)? I've heard a lot of bad things about eval...
Note that the above produces code like this:
[7, 7, 7, 7]
[3, 3, 3, 3]
etc. while I want something like
[1, 2, 3, 4]
[4, 3, 8, 4]
What does
Array#fill
do?According to MDN
You can use
Function#apply
,Array#map
,Math.floor()
,Math.random()
.In ES6,
Array#from
and Arrow function can be used.Array.apply(null, Array(6)).map(() => Math.floor(Math.random() * 9));
In ES5:
What is
Array.apply(null, Array(n))
? Cannew Array(n)
used here?Both the above code create new array of six elements, each element having value as
undefined
. However, when usednew
syntax, the created array is not iterable. To make the array iterable,Array.apply(null, Array(6))
syntax is used.If you have lodash included on page, it's really easy.
Note: This answer is inspired from Colin Toh's blog
`const t = Array.from({length: n}, mapArrowFx);
1)
const t10 = Array.from({length: 10}, (v, k) => k); [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2)
const tEven = Array.from({length: 10}, (v, k) => 2*k); [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
........
3)
let n=100; const tRandom= Array.from({length: n}, (v, k) => Math.floor(Math.random()*n));
...
This line of code will create a list of 4 of the same number because
fill
takes a single value and repeats it for the length of the list. What you want to do is run the random number generator each time:https://jsfiddle.net/t4jtjcde/