JavaScript 数组可能是我最喜欢的 JavaScript 原语。你可以用数组做各种很棒的事情:获取唯一值、克隆它们、清空它们等。从数组中获取随机值怎么样?
要从数组中获取随机项,您可以使用Math.random :
常量 arr = [
“一”,
“二”,
“三”,
“四”,
“告诉”,
“我”,
“那”,
“你”,
“爱”,
“我”,
“更多的”
];
const random1 = arr[(Math.floor(Math.random() * (arr.length)))]
const random2 = arr[(Math.floor(Math.random() * (arr.length)))]
const random3 = arr[(Math.floor(Math.random() * (arr.length)))]
const random4 = arr[(Math.floor(Math.random() * (arr.length)))]
控制台日志(随机 1,随机 2,随机 3,随机 4)
// 再告诉一个两个
至于何时需要数组中的随机值取决于您的个人应用程序。但是,很高兴知道您可以轻松获得随机值。 Array.prototype.random应该存在吗?
使用 JavaScript 获取随机数组项的帖子首先出现在David Walsh 博客上。