从JavaScript数组中获取随机值
从JavaScript数组中获取随机值
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
admin 更改状态以发布 2023年5月23日
如果您的项目中已经包含underscore或lodash,您可以使用_.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);