考虑:
var myArray = ['January', 'February', 'March'];
如何使用 JavaScript 从这个数组中选择一个随机值?
这是一个简单的单行:
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]);