如何从数组中获取一些随机元素? [英] How to get a number of random elements from an array?

查看:108
本文介绍了如何从数组中获取一些随机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何从javascript中的数组中随机访问元素".我发现了许多与此有关的链接.喜欢: 从JavaScript数组中获取随机项

I am working on 'how to access elements randomly from an array in javascript'. I found many links regarding this. Like: Get random item from JavaScript array

var item = items[Math.floor(Math.random()*items.length)];

但是在这种情况下,我们只能从数组中选择一项.如果我们需要多个元素,那么我们如何实现呢?我们如何从数组中获取多个元素?

But in this, we can choose only one item from the array. If we want more than one elements then how can we achieve this? How can we get more than one element from an array?

推荐答案

尝试此无损检查(以及快速)功能:

Try this non-destructive (and fast) function:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
    return result;
}

这篇关于如何从数组中获取一些随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆