考虑:

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

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


当前回答

Randojs使这更简单和可读:

console.log(rando(['January', 'February', 'March'])。值); < script src = " https://randojs.com/1.0.0.js " > < /脚本>

其他回答

如果你想把它写在一行上,就像Pascual的解决方案一样,另一个解决方案是使用ES6的find函数来写它(基于这样一个事实,从n个项目中随机选择一个的概率是1/n):

var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);

如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。

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

许多提供的解决方案将一个方法添加到一个特定的数组,这限制了它的使用仅限于该数组。这个解决方案是可重用的代码,适用于任何数组,并且可以是类型安全的。

打印稿

export function randChoice<T>(arr: Array<T>): T {
  return arr[Math.floor(Math.random() * arr.length)]
}

JavaScript

export function randChoice(arr) {
  return arr[Math.floor(Math.random() * arr.length)]
}

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

在数组中设置一个常量变量,然后在数组中的三个对象中随机选择另一个常量,然后函数简单地返回结果。

递归的独立函数,可以返回任意数量的项(与lodash.sampleSize相同):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}