Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a random string from an array [duplicate]

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....

like image 544
Mausoleum Avatar asked Sep 08 '11 15:09

Mausoleum


People also ask

How do you select a random string in an array?

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.

How do you select a random 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.


2 Answers

var textArray = [     'song1.ogg',     'song2.ogg' ]; var randomNumber = Math.floor(Math.random()*textArray.length);  audioElement.setAttribute('src', textArray[randomNumber]); 
like image 50
Gideon Avatar answered Sep 22 '22 20:09

Gideon


var randomIndex = Math.floor(Math.random() * textArray.length);  var randomElement = textArray[randomIndex]; 
like image 31
sberry Avatar answered Sep 25 '22 20:09

sberry