【问题标题】:How to select a number of random elements from an array? [duplicate]如何从数组中选择多个随机元素? [复制]
【发布时间】:2017-01-01 22:04:16
【问题描述】:
var array = ["one", "two", "three", "four", "five"];
var item = array[Math.floor(Math.random()*array.length)];

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

例如,不能只选择three,而应该是two five one

【问题讨论】:

  • 你想让它们与众不同吗?
  • @Oriol 是的,我希望他们与众不同
  • 首先创建一个数组来存储选定的项目var items=[]然后你可以将它填充到一个循环中,当你选择你的项目时,也可以从array拼接它,或者你可以使用嵌套的while循环,一个检查你的 items 数组中是否有
  • 尝试调整这个答案:stackoverflow.com/a/3943985/145346

标签: javascript arrays


【解决方案1】:

您可以使用一个虚拟数组进行计数,并使用数组的副本并拼接随机项而无需打乱数组。

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);

【讨论】:

  • 很高兴看到您的解决方案 :)
【解决方案2】:

你可以shuffle()array然后得到你需要的第一个X项目:

var array = ["one", "two", "three", "four", "five"];
var n = 3;
function shuffle(a) {
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
}
shuffle(array)
console.log(array.slice(0, 3))

洗牌功能取自这个问题:How can I shuffle an array?

如果您还需要原来的array,可以使用slice

var array = ["one", "two", "three", "four", "five"];
var n = 3;
function shuffle(a) {
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
}
array_tmp = array.slice(0)
shuffle(array_tmp)
console.log(array_tmp.slice(0, 3))
console.log(array)

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 2012-01-23
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多