从数组中随机取n个元素

//随机获取[min,max]的随机整数
let getRandomNumBetween = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

//从数组arr中,随机取nCount个元素,返回数组。可选择是否去重bQuChong
var getRandomArray = function(arr, nCount, bQuChong) {
    if (!(arr instanceof Array)) {
        return [];
    }
    let length = arr.length;
    let arrRes = [];
    nCount = length < nCount ? length : nCount;

    while (arrRes.length < nCount) {
        let randomIndex = getRandomNumBetween(0, length - 1);
        let item = arr[randomIndex];
        if (item) {
            if (bQuChong) {
                if (arrRes.indexOf(item) < 0) {
                    arrRes.push(item);
                }
            } else {
                arrRes.push(item);
            }
        }
    }

    return arrRes;
}

 

你可能感兴趣的:(JavaScript)