编辑代码

// 二维数组随机打乱,arr为二维数组
function shuffle(arr) {
    let rowLen = arr.length
    let colLen = arr[0].length
    let len = rowLen * colLen
    for (let i = len; i > 0; i--) {
        // 计算x时注意是Math.floor((i - 1) / colLen),而不是Math.floor((i - 1) / rowLen),下同
        let x = Math.floor((i - 1) / colLen)
        let y = (i - 1) % colLen
        let randLen = Math.floor(Math.random() * i)
        let randX = Math.floor(randLen / colLen)
        let randY = randLen % colLen
        let temp = arr[x][y]
        arr[x][y] = arr[randX][randY]
        arr[randX][randY] = temp
    }
    return arr
}

let arr = [[21, 11, 45], [56, 9, 66], [77, 89, 78], [68, 100, 120]]
console.log(shuffle(arr))