本文翻译自:Get random item from JavaScript array [duplicate]
This question already has answers here :
这个问题已经在这里有了答案 :
Closed 4 years ago .
4年前关闭。
var items = Array(523,3452,334,31,...5346);
How do I get random item from items
? 如何从items
获取随机items
?
#1楼
参考:https://stackoom.com/question/Oomm/从JavaScript数组中获取随机项-重复
#2楼
An alternate way would be to add a method to the Array prototype: 另一种方法是向Array原型添加一个方法:
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
var chosen_team = teams.random(teams.length)
alert(chosen_team)
#3楼
Use underscore (or loDash :)): 使用下划线(或loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];
// use _.sample
var randomElement = _.sample(randomArray);
// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];
Or to shuffle an entire array: 或改组整个数组:
// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
#4楼
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
Shorter: 更短:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
#5楼
const ArrayRandomModule = {
// get random item from array
random: function (array) {
return array[Math.random() * array.length | 0];
},
// [mutate]: extract from given array a random item
pick: function (array, i) {
return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
},
// [mutate]: shuffle the given array
shuffle: function (array) {
for (var i = array.length; i > 0; --i)
array.push(array.splice(Math.random() * i | 0, 1)[0]);
return array;
}
}
#6楼
Here's yet another way: 这是另一种方式:
function rand(items) {
return items[~~(items.length * Math.random())];
}