Let’s say I have an array of 100 integers that looks like this:
let hundred = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
By the way, here is the code that I used to generate this list of 100 integers in JavaScript (ES6):
let hundred = Array.from({length: 100}, (v, k) => k+1); console.log(hundred.toString());
This uses the JavaScript from() method. Here is what developer.mozilla.com says about the from() method:
The Array.from() method creates a new Array instance from an array-like or iterable object.
The from() method can also be used to create an array from a string. For example:
var myArr = Array.from("ABCDEFG");
yields
[A,B,C,D,E,F,G]
Now if I want to return a random number from this array, I can do so like this:
let rand = hundred[Math.floor(Math.random() * hundred.length)]; console.log('rand', rand); // or console.log('rand', hundred[rand])
which yields a different number from 1 to 100 every time it is run.
This code has three parts:
1. the inside call to Math.random()
Math.random() * hundred.length // or console.log(Math.random() * 100);
this yields a floating point number between 0 and length (100) . For example:
28.176629963901156
2. the middle call to Math.floor()
Math.floor(28.176629963901156);
This takes the result of step 1 and rounds it to the nearest integer. In this case 28.
3. the outer array index reference
hundred[28];
For more information about theĀ from()
method, see:
https://www.w3schools.com/jsref/jsref_from.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
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