从 JavaScript 数组中获取随机值

2022-08-29 22:07:57

考虑:

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

如何使用JavaScript从此数组中选择随机值?


答案 1

这是一个简单的单行:

const randomElement = array[Math.floor(Math.random() * array.length)];

例如:

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

答案 2

如果您的项目中已经包含下划线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);