Get a random item from a JavaScript array

1.5k2011 年提問 · James ·javascriptarraysrandom 主題:陣列與迴圈 → 在 Stack Overflow 看原文 ↗
var items = Array(523, 3452, 334, 31, ..., 5346);

How do I get random item from items?

重點答案

3.2k採納 by Kelly 原文 ↗
var item = items[Math.floor(Math.random()*items.length)];

1. solution: define Array prototype

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

var list = [2,3,5]
list.random()

2. solution: define custom function that accepts list and returns element

function get_random (list) {
  return list[Math.floor((Math.random()*list.length))];
}


get_random([2,3,5])

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];