考虑:

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

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


当前回答

如果你的项目中已经包含了下划线或lodash,你可以使用_.sample。

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

如果你需要随机获取一个以上的项,你可以将它作为第二个参数在下划线中传递:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

或者使用_。lodash中的sampleSize方法:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);

其他回答

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

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

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

递归的独立函数,可以返回任意数量的项(与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])
}

我真的很惊讶没有人尝试使用本机随机值:

array[Date.now()%array.length]

对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组

UPD

至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:

myArray[Date.now()%myArray.length]

简单功能:

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

获取随机元素的通用方法:

让some_array =[‘简’,2月,3月,4月,“可能”); Let months = random_elems(some_array, 3); console.log(个月); 函数random_elems(arr, count) { 让len = arrr .length; 让查找= {}; Let TMP = []; If (count > len) Count = len; 对于(设I = 0;I < count;我+ +){ 让指数; {做 index = ~~(Math.random() * len); } while(查找中的索引); 查找[index] = null; tmp.push (arr(指数)); } 返回tmp; }