2017-02-12 86 views
1

我在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   ] 
// [     ] 

您的帮助是非常感谢。谢谢。

回答

0

您可以使用slice为行元素获取独立元素。

while (numrows--) matrix[matrix.length] = row.map(a => a.slice()); 
//           ^^^^^^^^^^^^^^^^^^^ 

function createMatrix(numrows, numcols, initialValue = []) { 
 
    var matrix = []; var row = []; 
 
    while (numcols--) row[row.length] = initialValue; 
 
    while (numrows--) matrix[matrix.length] = row.map(a => a.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)

0

第一个问题是,你试图将相同的初始阵列initialValue的基准分配给具有行每一列:

while (numcols--) row[row.length] = initialValue; // <---- 

这就是为什么所有列充满了同样的价值。 第一个问题的解决方案是:

while (numcols--) row[row.length] = initialValue.slice(); 

第二个问题如果阵列包含嵌套阵列中,“克隆”将包含对旧数组引用。
这是发生在你的矩阵中的行在这条线的情况下:

while (numrows--) matrix[matrix.length] = row.slice(); // <--- 

用于第二问题的解决方案将是使用Array.protottype.map()功能克隆所有嵌套的数组:

while (numrows--) matrix[matrix.length] = row.map(function(arr){ return arr.slice(); }); 

现在,您将获得所需的输出:

A[1][2].unshift(7); 

[    ] 
[  7  ] 
[    ] 
0

感谢您的意见并回答所有人。非常感激。

我也得出了同样的结论,问题是由于'slice()'造成的浅拷贝。这是一个更简单的解决问题的实现,以防将来有人需要它:

function createMatrix(dimensions) { 
    var matrix = []; 

    for (var i = 0; i < dimensions[0]; ++i) 
     matrix[matrix.length] = (dimensions.length == 1 ? [] : createMatrix(dimensions.slice(1))); 

    return matrix; 
};