📌  相关文章
📜  javascript 从数组中获取 n 个随机元素 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:16.988000             🧑  作者: Mango

代码示例2
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;
}