这个嵌套循环如何得到这个输出?

发布于 2025-01-13 14:15:28 字数 992 浏览 4 评论 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, 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);

I have struggled to understand the output of this nested loop for a long time. I really want to understand what it does.

I would expect it to output: [ [ 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]

But the actual output is: [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]

After the first inner loop row contains two 0's and should be pushed to the newArray in the outer loop. It looks like this isn't happenening and I can't figure out why. The first element should be [0, 0], right?.

I really hope someone can see what I mean here and explain what's happening! Thank you!

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终止放荡 2025-01-20 14:15:28

您将 row 传递给循环的所有迭代。为了实现您想要的效果,行在循环的每次迭代中都必须是唯一的,因此您需要将其移动到第一个循环内。

为了更好地理解这个问题,请阅读有关 JavaScript 中的值和引用的更多信息:https://www.javascripttutorial.net/javascript-pass-by-value/#:~:text=JavaScript%20pass%2Dby%2Dvalue%20or%20pass%2Dby%2Dreference&text=It%20means%20that %20JavaScript%20 副本,%20%20%20 函数外部的变量%20

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);
    // Update n to get desired pattern
    n += 2
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

You're passing row to all the iterations of the loop. To achieve what you want, row must be unique through each iteration of the loop, so you need to move it inside the first loop.

To better understand the issue, read more about values and by references in JavaScript: https://www.javascripttutorial.net/javascript-pass-by-value/#:~:text=JavaScript%20pass%2Dby%2Dvalue%20or%20pass%2Dby%2Dreference&text=It%20means%20that%20JavaScript%20copies,variables%20outside%20of%20the%20function.

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);
    // Update n to get desired pattern
    n += 2
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

梦醒灬来后我 2025-01-20 14:15:28

这是因为 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);
});

That's because JavaScript objects (and arrays), are just a reference in memory. so you are creating a single array of arrays that share the same address in memory, because they share the same address, when you update it (Array.prototype.push), you are updating all of them. The solution is to create a new row in the first loop:

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);

Important note

This isn't a natural way of writing JavaScript, you can achive the same with:

const zeroArray = (m, n) => Array.from({ length : m }).map((value, index) => {
  return Array.from({ length : (index + 1) * n }).map(() => 0);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文