34

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

1

2 Answers 2

95
var textArray = [
    'song1.ogg',
    'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);

audioElement.setAttribute('src', textArray[randomNumber]);
Sign up to request clarification or add additional context in comments.

5 Comments

had a little spelling mistake (length should be without capital), but fixed it in my answer
Yeah thanks you told me. It didn't work first but now it does. Thanks! By the way is it really needed to put a semicolon after every line?
yes, you need a semicolon to terminate every statement in javascript. also, please mark Gidon's answer as correct if it solves your problem.
@jbabey: That is incorrect. JavaScript inserts semicolons automatically, but because it is not perfect, it does not always insert them at the right place. So, you don't have to use semicolons, but you really really should.
Thanks to you all. I marked it as correct. I forgot that becuase of the timespan I have to wait to do that...
22
var randomIndex = Math.floor(Math.random() * textArray.length); 
var randomElement = textArray[randomIndex];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.