如何从数组中选择多个随机元素?

2 javascript arrays

var array = ["one", "two", "three", "four", "five"];
var item = array[Math.floor(Math.random()*array.length)];
Run Code Online (Sandbox Code Playgroud)

上面的代码从数组中随机选择一个项目。但是,我怎么能让它一次从数组中选择 3 个随机元素,而不仅仅是一个。

而不是仅选择three例如,它应该类似于two five one.

Nin*_*olz 7

您可以使用虚拟数组进行计数和数组的副本,并在不改组数组的情况下拼接随机项目。

var array = ["one", "two", "three", "four", "five"],
    result = array.slice(0, 3).map(function () { 
        return this.splice(Math.floor(Math.random() * this.length), 1)[0];
    }, array.slice());

console.log(result);
Run Code Online (Sandbox Code Playgroud)