可能重复:
How can I return a random value from an array?
Getting random value from an array
如果你有一个数组:
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
我如何从这个数组中随机选择一个元素?
答案 0 :(得分:2)
var randomDay = days[Math.floor(Math.random()*days.length)]
document.write(randomDay);
答案 1 :(得分:1)
您可以使用
days[Math.floor(Math.random()*days.length)];
答案 2 :(得分:0)
如果你想要,你可以将它作为所有Array
s的通用函数,即
Array.prototype.getRandomElement = function () {
return this[Math.floor(Math.random() * this.length)];
};
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",
randomDay = days.getRandomElement();