js打乱数组 洗牌算法

531 阅读1分钟

利用while循环,取原数组随机一位放入新数组里面,再把原数组的那位删除,直到原数组没有元素位置

let arr = [1,2,3,4,5,6,7,8,9]
 function randRom(arr) {
    var res = []
     while (arr.length>0){
        let index = Math.floor(Math.random()*arr.length)
         res.push(arr[index])
         arr.splice(index,1)
     }
     return res
 }
 console.log(randRom(arr))

利用循环向另一个数组里面随机丢数据 如果这个数据另一个数组里面有了就增加循环

function randRom2(arr) {
    var res = []
    let num = arr.length
    while (num > 0) {
        num--
        let index = Math.floor(Math.random()*arr.length)
        if(!res.includes(arr[index])){
            res.push(arr[index])
        }else {
            if(res.length === arr.length){
                break
            }
            num++
        }
    }
    return res
}
console.log(randRom2(arr))

利用sort排序方式打乱数组

function randRom3(arr){
    arr.sort(0.5 - Math.random())
}