Possible Duplicate:
JavaScript: Getting random value from an array
Could someone help me on this topic? I've got this code.
var textArray = [ 'song1.ogg', 'song2.ogg' ] audioElement.setAttribute('src', textArray);
How can I randomly get one of those strings into my audio element?
Would be glad if someone can help....
We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.
Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.
var textArray = [ 'song1.ogg', 'song2.ogg' ]; var randomNumber = Math.floor(Math.random()*textArray.length); audioElement.setAttribute('src', textArray[randomNumber]);
var randomIndex = Math.floor(Math.random() * textArray.length); var randomElement = textArray[randomIndex];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With