简体   繁体   English

为什么嵌套在 map() function 中的 for 循环返回 NxN^2 边的数组而不是 NxN?

[英]Why does for loop nested in map() function return an array of side NxN^2 instead of NxN?

I am simply trying to initialize a 2D array of size N x N - where N = the boardSize prop - but when I write out the following, I instead get a 2D array of size N x N^2:我只是想初始化一个大小为 N x N 的二维数组 - 其中 N = boardSize 属性 - 但是当我写出以下内容时,我得到一个大小为 N x N^2 的二维数组:

let cells = new Array(this.props.boardSize).fill([]).map((e) => {
  let newRow = e;
  for (let i = 0; i < this.props.boardSize; i++) {
    newRow.push(this.intializeCell());
  }

  return newRow;
});

Why is this behavior happening?为什么会发生这种行为? Is it because I'm initializing an Array of size 6 with blank Array objects?是因为我用空白数组对象初始化一个大小为 6 的数组吗? Or is it some weird behavior I'm not noticing going on in the for loop?还是我没有注意到 for 循环中发生的一些奇怪行为?

I will mention that when I alter the code to the following, it works as intended:我会提到,当我将代码更改为以下内容时,它会按预期工作:

let cells = new Array(this.props.boardSize)
  .fill(new Array(this.props.boardSize).fill(0))
  .map((row) => {
    let newRow = row.map((_) => this.intializeCell());

    return newRow;
  });

The problem is that.fill is using the same array object for each row.问题是 that.fill 对每一行都使用相同的数组 object 。 Therefore, when you update the row by updating e in the map function, you are always adding to the same array.因此,当您通过更新 map function 中的 e 来更新行时,您总是添加到同一个数组中。

This would fix the problem.这将解决问题。

let cells = new Array(this.props.boardSize).fill([]).map((e) => {
  let newRow = [];
  for (let i = 0; i < this.props.boardSize; i++) {
    newRow.push(this.intializeCell());
  }

  return newRow;
});

.fill(value) fills the array with a copy of the same empty array N times. .fill(value) 用同一个空数组的副本填充数组 N 次。 So by adding N items to the same array N times, you end up with N^2 items.因此,通过将 N 项添加到同一个数组 N 次,最终得到 N^2 项。

Another example另一个例子

let test = new Array(3).fill([]);
test[0].push('a')
console.log(test)
// prints ['a','a','a']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM