There's a lot to cover, so let's break it down:
The Magic of Math.random
You're on the right track with Math.random
. It generates a number greater than or equal to 0 and less than 1. While it can technically return 0, the chances are incredibly slim (about 1 in 10 billion). An example result could be:
0.6687583869788796
Let's pause here for a moment.
Navigating Arrays and Their Indexes
In JavaScript, each item in an array has an index starting at 0. Here's a breakdown:
[ 'foo', 'bar', 'baz' ]
And their corresponding indexes:
name | index
-----|------
foo | 0
bar | 1
baz | 2
To access an item by its index, you use square brackets like this:
fooBarBazArray[0]; // foo
fooBarBazArray[2]; // baz
Understanding Array Length
An array's length is not the same as the largest index. It reflects the count of elements. For instance, the array above has a length of 3
:
['foo', 'bar', 'baz'].length; // Returns 3
Diving Deeper into Random Math
Now, let's examine randomizing using code like this:
Math.round(Math.random() * (mathematics.length-1))
This involves several steps:
Generating a Random Number
A random number is generated first.
Multiplying by the Array Length
The aim is to get a random array index, which requires subtracting 1 from the array length to reach the highest index.
Resolving Issues
The current calculation includes an unnecessary subtraction by 1. Adjusting the code simplifies it:
Math.random() * ['foo', 'bar', 'baz'].length
Running the updated code yields results such as:
2.1972009977325797
1.0244733088184148
0.1671080442611128
2.0442249791231006
1.8239217158406973
Wrapping Up
To obtain a random index, apply Math.floor
to convert decimals to integers:
2
0
2
1
2
By placing this within square brackets, you select an element at the random index from the array.
Further Reading / References
- Exploring Random Numbers
- Additional Solutions