考虑:

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

如何使用JavaScript从这个数组中选择一个随机值?


当前回答

这与@Jacob Relkin的解决方案类似,但更普遍:

这是ES2015:

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

该代码的工作原理是在0到数组长度之间选择一个随机数,然后返回该下标处的项。

其他回答

最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)

简单功能:

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();

编辑Array原型可能有害。这里是一个简单的函数来完成这项工作。

function getArrayRandomElement (arr) {
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  // The undefined will be returned if the empty array was passed
}

用法:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);

如果您有固定的值(如月份名称列表),并且想要一行解决方案

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?

通过在数组原型上增加一个方法,可以方便地获取随机值。

在本例中,您可以从数组中获取单个或多个随机值。

您可以通过单击代码片段按钮运行以测试代码。

Array.prototype.random = function(n){ if(n&&n>1){ const a = []; for(let i = 0;i<n;i++){ a.push(this[Math.floor(Math.random()*this.length)]); } return a; } else { return this[Math.floor(Math.random()*this.length)]; } } const mySampleArray = ['a','b','c','d','e','f','g','h']; mySampleArray.random(); // return any random value etc. 'a', 'b' mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d'] alert(mySampleArray.random()); alert(mySampleArray.random(3));