很長時間以來,我一直在努力理解這個嵌套回圈的輸出。我真的很想了解它的作用。
我希望它輸出:[ [ 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
但實際輸出是:[ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]
在第一個內回圈row包含兩個 0 之后,應該將其推到newArray外回圈中。看起來這沒有發生,我不知道為什么。第一個元素應該是[0, 0],對吧?
我真的希望有人能明白我的意思并解釋發生了什么!謝謝!
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i ) {
// Adds the m-th row into newArray
for (let j = 0; j < n; j ) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
uj5u.com熱心網友回復:
您將傳遞row給回圈的所有迭代。為了實作您想要的,行在回圈的每次迭代中都必須是唯一的,因此您需要將其移動到第一個回圈中。
為了更好地理解這個問題,請閱讀更多關于值和 JavaScript 中的參考:https ://www.javascripttutorial.net/javascript-pass-by-value/#:~:text=JavaScript pass-by-value or% 20pass-by-reference&text=It means that JavaScript copies,variables outside of the function .
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
for (let i = 0; i < m; i ) {
let row = [];
// Adds the m-th row into newArray
for (let j = 0; j < n; j ) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
uj5u.com熱心網友回復:
那是因為 JavaScript 物件(和陣列)只是記憶體中的一個參考。所以你正在創建一個在記憶體中共享相同地址的陣列陣列,因為它們共享相同的地址,當你更新它(Array.prototype.push)時,你正在更新它們。解決方案是在第一個回圈中創建一個新行:
function zeroArray(m, n) {
const newArray = [];
for (let i = 0; i < m; i ) {
// If this isn't the first run, take the last value of row
const prevRow = i > 0 ? newArray[i-1] : [];
const row = [...prevRow]; // By using the spread operator(...), you can copy an array
for (let j = 0; j < n; j ) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
重要的提示
這不是撰寫 JavaScript 的自然方式,您可以通過以下方式實作:
const zeroArray = (m, n) => Array.from({ length : m }).map((value, index) => {
return Array.from({ length : (index 1) * n }).map(() => 0);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/442918.html
標籤:javascript 循环 嵌套的
