从 JavaScript 数组中获取随机值

新手上路,请多包涵

考虑:

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

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

原文由 Sarah 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 781
2 个回答

这是一个简单的单行:

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

原文由 Jacob Relkin 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Brendan Nee 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题