我在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 ]
// [ ]
您的帮助是非常感谢。谢谢。