samedi 23 janvier 2016

Creating array of length n with random numbers in JavaScript

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...




Aucun commentaire:

Enregistrer un commentaire