How to get a random item from a JavaScript array
Hello guys, if you want to get a random item from an array in JavaScript, then in this article, you will know that how you can easily select a random value from an array using JavaScript.
You can access every item of an array using its index. For example,you want to get the first element of an array, use array[0],to get the second item use array[1], and so on.
- Math.random() method is used to get a random number between 0 to 1 (1 exclusive).
- To get the numbers between 0 to array length, multiply the Math.random() value by array length.
- The result will be a decimal number. So, round the result to the nearest integer that is equal to or lower than the random value using Math.floor() method.
save
listen
AI Answer
How to get a random item from a JavaScript array
1
Hello guys, if you want to get a random item from an array in JavaScript, then in this a…
asked
Apu
1 answers
2915
Hello guys, if you want to get a random item from an array in JavaScript, then in this a…
Answer Link
answered
Apu
<script>
let list = [2,3,5];
let item = list.sort(function() {return 0.5 - Math.random()});
alert(item[0]) ;
</script>
item is an array so use item[0] to get the first item.