如何用JavaScript获得一个随机数组项目

83 阅读1分钟

JavaScript数组可能是我在JavaScript中最喜欢的基元。 你可以用数组做各种了不起的事情:获得唯一的值克隆它们清空它们,等等。 那么,从数组中获取一个随机值呢?

要从一个数组中获得一个随机项,你可以使用Math.random

const arr = [
    "one",
    "two",
    "three",
    "four",
    "tell",
    "me",
    "that",
    "you",
    "love",
    "me",
    "more"
];
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)))]

console.log(random1, random2, random3, random4)
// tell one more two

至于什么时候需要从数组中获得随机值,则取决于你的个人应用。 不过,很高兴知道你可以很容易地得到一个随机值。 Array.prototype.random 应该存在吗?