数组随机排序

var arr = [1,2,3,4,5,6,7,8,9,10]; 
function randomSort1(arr) {
    for (let i = 0, len = arr.length; i < len; i++) {
        let j = Math.floor(Math.random() * len);
        [ arr[i], arr[j] ] = [ arr[j], arr[i] ];
    }
    return arr;
}
console.log(randomSort1(arr))
let arr = [1,2,3,4,5,6,7,8,9,10]; 
function randomSort2(arr) {
    let randomArr = [];
    while (arr.length > 0) {
        let num = Math.floor(Math.random() * arr.length);
        randomArr.push(arr[num]);
        arr.splice(num, 1);
    }
    return randomArr;
}
console.log(randomSort2(arr))
let arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
    return Math.random() - 0.5;
})
console.log(arr);

你可能感兴趣的:(数组随机排序)