Get random item from JavaScript array [duplicate]

2018-12-31 05:21发布

This question already has an answer here:

var items = Array(523,3452,334,31,...5346);

How do I get random item from items?

13条回答
长期被迫恋爱
2楼-- · 2018-12-31 05:58
var rndval=items[Math.floor(Math.random()*items.length)];
查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 05:59

Use underscore (or 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楼-- · 2018-12-31 06:08

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]
查看更多
牵手、夕阳
5楼-- · 2018-12-31 06:11
// 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];
查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 06:14
var item = items[Math.floor(Math.random()*items.length)];
查看更多
零度萤火
7楼-- · 2018-12-31 06:15

Here's yet another way:

function rand(items) {
    return items[~~(items.length * Math.random())];
}
查看更多
登录 后发表回答