我在javascript中創建了一個二維矩陣,其中矩陣中的每個元素都是一個空數組。多維矩陣上的元素元素操作
問題是,無論何時我嘗試推送到矩陣中的某個元素,推送都會應用於整個矩陣,而不是特定元素。
下面是代碼:
function createMatrix(numrows, numcols, initialValue = []) {
var matrix = []; var row = [];
while (numcols--) row[row.length] = initialValue;
while (numrows--) matrix[matrix.length] = row.slice();
return matrix;
};
function printMatrix(matrix) {
var output = '';
for (var i = 0; i < matrix.length; i++) {
output += '[';
for (var j = 0; j < matrix[i].length; j++) {
output += ' ' + matrix[i][j];
}
output += ' ]\n';
}
console.log(output);
};
// Example code
var A = createMatrix(3,6, []);
printMatrix(A)
// This is the output:
// [ ]
// [ ]
// [ ]
// For example, we now try to add number 7 to the empty array at [1][2]
A[1][2].unshift(7);
// Let's see how the matrix looks like:
printMatrix(A)
// [ 7 7 7 7 7 7 ]
// [ 7 7 7 7 7 7 ]
// [ 7 7 7 7 7 7 ]
上述矩陣是錯誤的。而不是僅應用於單個元素的推送,它將應用於整個矩陣。換句話說,正確的輸出應該是這樣的:
// [ ]
// [ 7 ]
// [ ]
您的幫助是非常感謝。謝謝。