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
.
您可以使用虚拟数组进行计数和数组的副本,并在不改组数组的情况下拼接随机项目。
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)
归档时间: |
|
查看次数: |
3299 次 |
最近记录: |