2017-02-12 90 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; 
};