从JavaScript数组中获取随机值

35 浏览
0 Comments

从JavaScript数组中获取随机值

考虑:

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

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

admin 更改状态以发布 2023年5月23日
0
0 Comments

如果您的项目中已经包含underscorelodash,您可以使用_.sample

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

如果您需要随机获取多个项目,您可以在underscore中将其作为第二个参数传递:

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

0
0 Comments

这只是一个简单的一行代码:

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

0