ช่วยอธิบายข้อนี้ทีครับ

บอกเราว่าเกิดอะไรขึ้น:
อธิบายปัญหาของคุณโดยละเอียดที่นี่

  **รหัสของคุณ**

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
  row = [];
  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);

  **ข้อมูลเบราว์เซอร์ของคุณ:**

ตัวแทนผู้ใช้คือ: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15

Challenge: Use Caution When Reinitializing Variables Inside a Loop

ไปสู่ the challenge:

จากโจทย์ นี่เขาให้สร้าง array 2 มิติที่มี m rows และ n columns และบรรจุเลข 0 ทั้งหมด ใช่ไหมครับ ซึ่งใน code ตัวอย่าง กำหนด m,n เป็น 3,2 ตามลำดับใช่ไหมครับ ซึ่งผลลัพธ์ที่ควรจะเป็น หาก ฟังก์ชันทำงานถูกต้อง คือ [[0, 0], [0, 0], [0, 0]] แต่โจทย์บอกว่า ตอนนี้ฟังก์ชันนี้แสดงผลไม่ถูกต้อง และสิ่งที่คุณทำนี่ก็คือ เติม row=[] ลงไปก่อนที่จะขึ้น loop ข้างในใช่ไหมครับ คุณอาจจะสงสัยว่าทำไมการกระทำดังกล่าว มันถึงทำให้ฟังก์ชันทำงานอย่างถูกต้องใช่ไหมครับ อย่างแรกเลย งั้นเรามาดู โค้ดอันเดิมที่ โจทย์ให้มาแล้วทำความเข้าใจกันก่อนครับ หน้าตามันจะเป็นประมาณนี้ใช่ไหมครับ ในที่นี่ผมลองเติม console.log() บางที่เพื่อดูว่าปกติแล้วค่า row เป็นเท่าไร

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
  console.log("เริ่มรอบที่",i+1,row)
  for (let j = 0; j < n; j++) {
    // Pushes n zeroes into the current row to create the columns
    row.push(0);
  }
  console.log("จบรอบที่",i+1,row)
  console.log('----------------------')
  // Pushes the current row, which now has n zeroes in it, to the array
  newArray.push(row);
}
return newArray;
}

ซึ่งเมื่อเรารัน code ดังกล่าวจะได้จะแสดงผลดังนี้

เริ่มรอบที่ 1 []
จบรอบที่ 1 [ 0, 0 ]
----------------------
เริ่มรอบที่ 2 [ 0, 0 ]
จบรอบที่ 2 [ 0, 0, 0, 0 ]
----------------------
เริ่มรอบที่ 3 [ 0, 0, 0, 0 ]
จบรอบที่ 3 [ 0, 0, 0, 0, 0, 0 ]
----------------------

จะเห็นว่า หากเราไม่ set row=[] ตอนเริ่มรอบที่ 2 ใน row จะมี item อยู่แล้ว ซึ่งจะทำให้ เราไม่มีทางได้ผลลัพธ์ที่โจทย์ต้องการซึ่งก็คือ [[0, 0], [0, 0], [0, 0]] ได้ การset row=[] จะทำให้ตอนเริ่มรอบที่ 2 จะทำให้ค่าเป็น []

เริ่มรอบที่ 1 []
จบรอบที่ 1 [ 0, 0 ]
----------------------
เริ่มรอบที่ 2 []
จบรอบที่ 2 [ 0, 0 ]
----------------------
เริ่มรอบที่ 3 []
จบรอบที่ 3 [ 0, 0 ]
----------------------

น่าจะประมาณนี้อ่ะครับ ผมเองก็ไม่ค่อยถนัดการอธิบายด้วย

พอเหนภาพขึ้นมาหน่อยครับ ประมาณว่าทุกๆรอบ เราต้องสร้าง[] ขึ้นมาเพื่อรับค่า0ใหม่ใช่ไหมครับ

ใช่แล้วครับผม เพื่อให้ได้สิ่งที่โจทย์ต้องการแหละครับผม

1 Likes