我有输入:
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]
我不知道为什么 1
和 2
中有双倍的 5
和双倍的 19
显然我是做错事。我认为问题出在我创建新数组的方式上。
有人可以解释一下这里发生了什么吗?
最佳答案
根据documentation 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 个空条目。
关于javascript - 从边数组创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58767259/