【发布时间】:2017-02-12 20:29:48
【问题描述】:
我在 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 ]
// [ ]
非常感谢您的帮助。谢谢。
【问题讨论】:
标签: javascript arrays matrix multidimensional-array