PDA

View Full Version : My arrays keep copying each other!



Boondogger
June 18th, 2004, 04:19 PM
This is probably something really simple but I have this multi-dimensional array which holds vital data. At one point in my program I need to copy the array so that I can sort it numerically and display the data, without permanently altering the original array order. I thought okay, create a new array and copy the original array data into it. Here is the code:

MyArrayCopy = new Array();
MyArrayCopy = MyArray;
MyArrayCopy.sort(function (b,a){return b [3] - a [3]});
MyArrayCopy.reverse();

Then I display what's in MyArrayCopy.

Bizarrely, when I go back to another part of the program I find that the data in the original MyArray has been changed too. Can anyone explain this and suggest how I can get round it?

Boondogger

ScriptFlipper
June 18th, 2004, 08:11 PM
Yes I can explain it :)
When you write

MyArrayCopy = MyArray;

you tell Flash that you want to refer to the array MyArray by a different name (which is MyArrayCopy). You do not copy an array by writing that.
To copy an array, you would have to do something like this:



MyArrayCopy = new Array();
for (var i=0; i<MyArray.length; i++) {
MyArrayCopy[i] = MyArray[i];
}


That will copy the array entry by entry. That is the only way of duplicating arrays that I know of. ;)

Cheers :)

claudio
June 18th, 2004, 08:23 PM
MyArrayCopy = MyArray.slice();

ScriptFlipper
June 18th, 2004, 08:35 PM
That's wonderful claudio, I didn't know that :)
(i.e. I've got to check out ActionScript Dictionary when I get the time to :) )

claudio
June 18th, 2004, 08:37 PM
Or best of kirupa, there's a thread with some tricks over there, let me find the link.

[edit] here http://www.kirupaforum.com/forums/showthread.php?t=14268

Boondogger
June 19th, 2004, 06:13 AM
Fantastic Claudio! Thanks for that, and thanks to ScriptFlipper too. That works fine. I knew you could use slice to copy parts of an array but I hadn't realise you could use it to copy the whole thing. Duh!

Thanks again

Boondogger

ScriptFlipper
June 19th, 2004, 07:43 AM
cheers claudio, I'll check it out :)

claudio
June 19th, 2004, 10:03 AM
Anytime guys :)