Getting a random value from a JavaScript array

2018-12-31 00:34发布

Consider:

var myArray = ['January', 'February', 'March'];    

How can I select a random value from this array using JavaScript?

标签: javascript
23条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 01:06

A generic way to get random element(s):

let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
let months = random_elems(some_array, 3);

console.log(months);

function random_elems(arr, count) {
  let len = arr.length;
  let lookup = {};
  let tmp = [];

  if (count > len)
    count = len;

  for (let i = 0; i < count; i++) {
    let index;
    do {
      index = ~~(Math.random() * len);
    } while (index in lookup);
    lookup[index] = null;
    tmp.push(arr[index]);
  }

  return tmp;
}

查看更多
低头抚发
3楼-- · 2018-12-31 01:07

Simple Function :

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
查看更多
泪湿衣
4楼-- · 2018-12-31 01:07

static generateMonth() { 
const theDate = ['January', 'February', 'March']; 
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};

You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.

查看更多
还给你的自由
5楼-- · 2018-12-31 01:08

This is similar to, but more general than, @Jacob Relkin's solution:

This is ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.

查看更多
妖精总统
6楼-- · 2018-12-31 01:10
var rand = myArray[Math.floor(Math.random() * myArray.length)];
查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 01:11

If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function (based on the fact, that the probability of randomly selecting one out of n items is 1/n):

var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (floor(random()*length and using a seperate function) are your way to go.

查看更多
登录 后发表回答