从数组中选择一个随机字符串[重复]

时间:2022-10-19 03:38:06

Possible Duplicate:
JavaScript: Getting random value from an array

可能重复:JavaScript:从数组中获取随机值

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

如果有人可以帮忙,我会很高兴....

2 个解决方案

#1


48  

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

audioElement.setAttribute('src', textArray[randomNumber]);

#2


9  

var randomIndex = Math.floor(Math.random() * textArray.length); 
var randomElement = textArray[randomIndex];

#1


48  

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

audioElement.setAttribute('src', textArray[randomNumber]);

#2


9  

var randomIndex = Math.floor(Math.random() * textArray.length); 
var randomElement = textArray[randomIndex];