小编典典

从 JavaScript 数组中获取随机值

all

考虑:

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

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


阅读 115

收藏
2022-02-28

共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]);
2022-02-28