PDA

View Full Version : 2 2D Arrays ending up being the same, when For-loop modifies one...



DrRobot
August 25th, 2008, 02:21 PM
Alright, so i'm doing some minor data copying from another array, and for some reason both arrays end up being the same. i never really change any properties of the first array...
here is my class:


package
{
import flash.display.Sprite;
import flash.events.Event;

public class Main extends Sprite
{
public var current:Array = [];
public var map:Array = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];

public function Main():void
{
testFunk();
}
private function testFunk():void
{
trace(map[0]);
for (var r:int = 0; r < 9; r++)
{
current.push(map[r]);
current[current.length-1].splice(9, 4);
for (var c:int = 0; c < 10; c++)
{
current[r][c] = 2;
}
}
trace(map[0]);
trace(current[0]);
trace(map);
}
}
}


and the traces output as:


[Capturing traces with FDB]
0,0,0,0,0,0,0,0,0,0,0,0,0,0
2,2,2,2,2,2,2,2,2,2
2,2,2,2,2,2,2,2,2,2
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0


why did map turn into current? what's the deal with this?

wvxvw
August 25th, 2008, 03:12 PM
By doing this:

current.push(map[r]); You've made both arrays the same. Just change it to:

current.push(map[r].slice());