Introduction
In JavaScript, we may wish to get a random value from an array. In this post, we'll look at how to do it.
How to get a random value from a JavaScript array
To get a random value from a JavaScript array we can use Math.floor()
and Math.random()
functions:
In the following example, we use the Math.random()
function to get a pseudo-random number between 0 and 1. Then we multiply that value by array.length
to get a random value no greater than the size of the array. Finally, we used Math.floor()
that rounds down a given number.
The random
variable contains a random index of frontbackend
array.
Conclusion
In this post, we presented the best way to get a random value from a JavaScript array.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}