数组 – 我需要为我创建的2D数组添加一个值

所以我使用以下代码创建了一个2D数组:

var grid:Array = [
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
]

我有一个按钮(理论上)将一个值拼接到每一行,因此在宽度方面扩展网格.然而,这个问题似乎并不在我的代码中扩展它,而是在我将垂直增量和水平增加相结合时.

这是我试图用于高度增加的当前代码:

var insertTo:int = 1;

var temp:Array = grid[0];

grid.splice(1, 0, temp);

这是我试图用于宽度增加的当前代码:

for (var i:int = 0; i < grid.length; i++){

    var insertTo:int = 1;

    grid[i].splice(insertTo, 0, 1); 

}

单击高度按钮后的当前意外结果,然后是宽度按钮(我有遍历的痕迹):

After height increase:
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

After width increase:
1,1,1,1,1,1
1,1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1

这是反向执行相同操作后的预期结果:

After width increase:
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1

After height increase:
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1

为什么它以单向而非另一种方式工作,我该如何解决?

最佳答案 你必须克隆数组befor插入它作为一个新的值

The Array class has no built-in method for making copies of arrays.
You can create a shallow copy of an array by calling either the
concat() or slice() methods with no arguments. In a shallow copy, if
the original array has elements that are objects, only the references
to the objects are copied rather than the objects themselves. The copy
points to the same objects as the original does. Any changes made to
the objects are reflected in both arrays.

var insertTo:int = 1;

var temp:Array = grid[0].concat(); // clone

grid.splice(1, 0, temp);
点赞