JavaScript(JS) JS get random item from an array
https://www.theitroad.com
To get a random item from an array in JavaScript/JS, you can use the Math.random()
function to generate a random index within the bounds of the array, and then return the item at that index. Here is an example function:
function getRandomItem(array) { return array[Math.floor(Math.random() * array.length)]; }
This function takes an array as its argument, generates a random index by multiplying Math.random()
by the length of the array and rounding down using Math.floor()
, and then returns the item at that index.
You can then call this function with an array to get a random item from it. For example:
const myArray = ['apple', 'banana', 'cherry', 'date']; const randomItem = getRandomItem(myArray); console.log(randomItem); // Output: e.g. "banana"
Note that this function assumes that the array is not empty. If the array may be empty, you should add additional logic to handle this case (e.g. returning undefined
or throwing an error).