js get random string from array code example
Example 1: javascript how to get a random element from an array
var items = ['Yes', 'No', 'Maybe'];
var item = items[Math.floor(Math.random() * items.length)];
Example 2: pick random string from array javascript
var groceries = [
'milk',
'coriander',
'cucumber',
'eggplant'
]
let mygroceries = groceries[Math.floor(Math.random() * groceries.length)]
console.log(mygroceries)
Example 3: random string from array javascript
var textArray = [
'song1.ogg',
'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
Example 4: get random elements from array javascript
array.sort(() => Math.random() - Math.random()).slice(0, n)
Example 5: js random string from array
const randomElement = array[Math.floor(Math.random() * array.length)];
Example 6: javascript random text from array
var textArray = [
'song1.ogg',
'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
audioElement.setAttribute('src', textArray[randomNumber]);