我正在尝试清理一些代码,但我不明白为什么这两种声明和填充空多维数组的方法会产生不同的结果。
let sample = [
[0, 0],
[1, 0]]
function transpose(array) {
let transposed = []
for (let i = 0; i < array.length; i++) {
transposed.push([])
}
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
transposed[j].push(array[i][j])
}
}
return transposed
}
function alternateTranspose(array) {
let transposed = Array(array.length).fill([])
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
transposed[j].push(array[i][j])
}
}
return transposed
}
原始函数返回: [[0,1], [0,0]]
但是重构的代码产生: [[0,0,1,0], [0,0,1,0]]