31

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

Community
  • 1
  • 1
Mausoleum
  • 411
  • 2
  • 5
  • 8

2 Answers2

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

audioElement.setAttribute('src', textArray[randomNumber]);
Gideon
  • 18,251
  • 5
  • 45
  • 64
  • 1
    had a little spelling mistake (length should be without capital), but fixed it in my answer – Gideon Sep 08 '11 at 15:18
  • 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? – Mausoleum Sep 08 '11 at 15:21
  • 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 Sep 08 '11 at 15:34
  • @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*. – Felix Kling Sep 08 '11 at 15:39
  • Thanks to you all. I marked it as correct. I forgot that becuase of the timespan I have to wait to do that... – Mausoleum Sep 10 '11 at 09:14
19
var randomIndex = Math.floor(Math.random() * textArray.length); 
var randomElement = textArray[randomIndex];
sberry
  • 128,281
  • 18
  • 138
  • 165