首页 > 解决方案 > 从边数组创建二维数组

问题描述

我有输入:

const topMatrix = [ 1, 2, 3, 4 ] ;
const leftMatrix = [ 0, 5, 10 ] ;
const rightMatrix = [ 9, 14, 19 ] ;
const bottomMatrix = [ 15, 16, 17, 18 ];

从上面的数组我想创建这样的数组:

[
    [1, 2, 3, 4, 9],
    [0, empty, empty, empty, 14],
    [5, empty, empty, empty, 19],
    [10, 15, 16, 17, 18]
]

所以顶部和底部几乎相同。

然后左列我只需要从 1 移到最后一个(不包括 0)。

然后右列我只需要从 0 推到最后一个 - 1 (不包括最后一个)。

到目前为止我所做的是:

const topMatrix = [ 1, 2, 3, 4 ] ;
const leftMatrix = [ 0, 5, 10 ] ;
const rightMatrix = [ 9, 14, 19 ] ;
const bottomMatrix = [ 15, 16, 17, 18 ];

const combineEdges = (top, left, right, bottom) => {
  const newArray = new Array(4);
  newArray.fill(new Array(4))

  //fill top and bottom
  newArray[0] = top;
  newArray[newArray.length - 1] = bottom;

  //fill left
  for(let i = 0, l = left.length; i < l; i++) {
    if(newArray[i + 1]) {
      newArray[i + 1].unshift(left[i]);
    }
  }

  //fill right
  for(let i = 0, l = right.length; i < l; i++) {
    if(newArray[i]) {
      newArray[i].push(right[i]);
    }
  }

  return newArray;
}

console.log(
  combineEdges(topMatrix, leftMatrix, rightMatrix, bottomMatrix)
)

现在我遇到了问题,因为我创建了数组“虚拟” .fill,这导致它的行为对我来说很奇怪。例如,这个填充左循环是不移动元素并出于某种我完全不理解的原因复制 5。

目前的输出是:

0: (5) [1, 2, 3, 4, 9]
1: (8) [5, 0, empty × 4, 14, 19]
2: (8) [5, 0, empty × 4, 14, 19]
3: (5) [10, 15, 16, 17, 18]

我不知道为什么会出现翻倍51翻倍2显然19我做错了什么。我认为问题在于我创建新数组的方式。

有人可以解释这里发生了什么吗?

标签: javascriptarrays

解决方案


根据文档 Array.fill() 用静态组件填充您的数组。这意味着你用相同的数组填充你的数组 4 次。然后在位置 0 和 3 而不是 1 和 2 覆盖它。

由于这是位置 1 和 2 的相同数组,因此您将相同的数字添加到两个数组。

你想删除

newArray.fill(new Array(4))

而是手动填写

  //fill top and bottom
  newArray[0] = top;
  newArray[1] = new Array(3);
  newArray[2] = new Array(3);
  newArray[newArray.length - 1] = bottom;

我还将它调整为 new Array(3) 因为在您的示例中,您希望中​​间有 3 个空条目。


推荐阅读