SOURCE

//使用嵌套循环
function convertTo2DArray(arr,row,col) {
    if(arr.length !== row * col) {
        throw new Error('Array length must be equal')
    }
    let results = [];
    for(let i =0;i<row;i++) {
        results.push(arr.slice(i*col,(i+1)*col))
    }
    return results
}

function convertTo2DArray2(arr, rows, cols) {
    if (arr.length !== rows * cols) {
        throw new Error("Array length must be equal to rows * cols");
    }
    
    return Array.from({ length: rows }, (_, i) => 
        arr.slice(i * cols, (i + 1) * cols)
    );
}
let oneDArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let twoDArray = convertTo2DArray2(oneDArray, 3, 3);
console.log(twoDArray);
console 命令行工具 X clear

                    
>
console