如何得到n个从数组中随机元素无 [英] How to get n no elements randomly from an array

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

问题描述

我的工作'如何从在JavaScript数组访问随机元素。我发现关于这个环节多。喜欢:
从获得使用jQuery数组随机项

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 array with jQuery

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

问:但是,在这一点,我们可以选择从array.If我们想要一个以上的元素那么如何才能请仅仅从这句话实现this.So只有一个项目,我们怎样才能得到更多的不是从阵列中的一个元素。

Question: 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.So please just from this statement how can we get more than one elements 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;
    }
    return result;
}

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

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