gpt4 book ai didi

arrays - 我需要向我创建的二维数组添加一个值

转载 作者:行者123 更新时间:2023-12-02 06:42:00 27 4
gpt4 key购买 nike

所以我用以下代码创建了一个二维数组:

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

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

最佳答案

您必须先克隆数组,然后才能将其作为新值插入

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

关于arrays - 我需要向我创建的二维数组添加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com