Let’s say I want to create a list of 10 numbers that are between the values of 0 and 1. This can be done with a simple for loop. For example:
let length = 10; let max = 1; let randArray = []; for (i=0; i < length; i++) { randArray.push(Math.random(max)); } console.log(randArray);
Setting the max value to 1 gives me only random values between 0 and 1. Setting the length to 10 gives me a list of 10 numbers. This yields:
[0.515654184126071, 0.3903385797823882, 0.9408518825018701, 0.08469998671516599, 0.2765966591556014, 0.20919957282624446, 0.9498787982265717, 0.5195513802386978, 0.7100803314063749, 0.03271176762225736]
Now instead of values between 0 and 1, lets say I want values from 1 to 100 and I want no decimals:
let length = 10; let max = 100; let randArray = []; for (i=0; i < length; i++) { randArray.push(Math.round(Math.random() * max)); } console.log(randArray);
Here I wrapped the Math.random()
function in a Math.round()
function (so there are no decimals), and multiplied each number by the max. The result is:
[75, 22, 66, 20, 24, 86, 66, 6, 59, 75]
For more information about Math.random(), see:
https://www.w3schools.com/jsref/jsref_random.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
For more information about Math.round(), see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round