Home >Web Front-end >JS Tutorial >How to Get a Random Element from a JavaScript Array?
How to Retrieve a Random Element from a JavaScript Array
Similar to a question raised in a different thread, this article delves into the topic of obtaining random items from JavaScript arrays. Consider the example array items with numerous elements.
var items = Array(523, 3452, 334, 31, ..., 5346);
The goal is to extract a random item from this array. To achieve this, we leverage the following code snippet:
var item = items[Math.floor(Math.random() * items.length)];
Let's break down the code:
By combining these elements, we obtain a random item from the input array.
The above is the detailed content of How to Get a Random Element from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!