考虑:

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

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


当前回答

您可以考虑在Array原型上定义一个函数,以便创建一个返回随机元素的方法[].sample()。

首先,要定义原型函数,将以下代码片段放入代码中:

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

之后,要从数组中随机抽取一个元素,只需调用.sample():

[1,2,3,4].sample() //=> a random element

我将根据CC0 1.0许可证的条款将这些代码片段发布到公共领域。

其他回答

假设你想随机选择一件与上次不同的物品(不是真的随机,但仍然是一个常见的要求)……

/**
 * Return a random element from an array that is
 * different than `last` (as long as the array has > 1 items). 
 * Return null if the array is empty.
*/
function getRandomDifferent(arr, last = undefined) {
  if (arr.length === 0) {
    return null;
  } else if (arr.length === 1) {
    return arr[0];
  } else {
    let num = 0;
    do {
      num = Math.floor(Math.random() * arr.length);
    } while (arr[num] === last);
    return arr[num];
  }
}

实现如下:

const arr = [1,2,3];
const r1 = getRandomDifferent(arr);
const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.

编辑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 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.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));

~~比Math.Floor()快得多,所以当涉及到使用UI元素生成输出的性能优化时,~~赢得了比赛。更多信息

var rand = myArray[~~(Math.random() * myArray.length)];

但是,如果您知道数组将有数百万个元素,那么您可能需要在位操作符和Math.Floor()之间重新考虑,因为位操作符对大数字的表现很奇怪。请参阅下面的输出示例。

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343