SOURCE


//法1: 生成一个随机数组

// 循环调用
function getArr(n) {
    let arr = [];
    for (let i =0; i< n; i++) {
        let _tmp = Math.floor(Math.random()*n);
        !arr.includes(_tmp) && arr.push(_tmp);
    }
    if (arr.length < n) {
       return getArr(n); 
    }
    return arr;
}

let arr = getArr(5);
console.log("arr1:", arr);


// sort

function getArr2(n) {
    let arr = [];
    while(n > 0) {
        arr.push(n -1);
        n--;
    }
    return arr.sort(() => Math.random() - 0.5);
}
let arr2 = getArr2(5);
console.log('arr2:', arr2);


function shuffle(arr) {
    let i = arr.length;
    while(--i) {
        let j = Math.floor(Math.random() * i);
        [arr[j], arr[i]] = [arr[i], arr[j]]
    }
    console.log(arr);
}
shuffle([1,2,3,4,5]);

 


console 命令行工具 X clear

                    
>
console