PDA

View Full Version : manipulating arrays


williamfawcett
11-25-2003, 07:46 PM
Hi all,

can anyone explain to me how this works (or rather, why it doesn't work the way I expect it to):

arrayA = [0,1,2,3,4,5,6,7,8,9];
arrayB = [];

function savePreviousArray () {
arrayB = arrayA;
trace ("savePreviousArray called\narrayB is "+arrayB);
}

_root.button1_mc.onPress = function () {
trace ("button1 pressed\narrayA is: \n"+arrayA);
trace ("arrayB is: \n"+arrayB);
}

_root.button2_mc.onPress = function () {
savePreviousArray ();
arrayA.splice (-1);
trace ("button2 pressed\narrayA is now: \n"+arrayA);
}

So, you've got 2 arrays, one starts full (0-9), one empty. Button1 just tells you what's in them whenever you ask. Button2 invokes the savePreviousArray function that justs assigns arrayA to ArrayB, then goes back and chops an element off the end (sorry if I'm stating the obvious, but I want to make sure I not missing anything). Then it traces the new value of arrayA. Yet, when you click button1 again, arrayB has been updated, without me asking for it.

Am I missing something obvious? All I want to do is store a copy of arrayA before manipulating it, but I can't seem to put my finger on the trick...

Bill

pixelwit
11-25-2003, 09:29 PM
I think you need to get a handle on primitive and composite datatypes.

When you set a variable to "equal" a composite datatype such as a movieclip or an array the composite datatype isn't duplicated but "referenced". A reference isn't much more than a pointer. For example, when you say "arrayB = arrayA;" you turn arrayB into a reference to arrayA. This now means when you ask what's in the second index of arrayB, arrayB just looks over at arrayA and says it has whatever arrayB has in its second index.

To actually duplicate the content of one array and place it in another array you can use the array's slice method like this:arrayA = [0,1,2,3,4,5,6,7,8,9];
arrayB = arrayA.slice();
arrayB[1] = "cow";
trace(arrayA);
trace(arrayB);Hope it helps.

-PiXELWiT
http://www.pixelwit.com

williamfawcett
11-26-2003, 10:13 AM
I get it.

I can add a redo function to http://www.williamfawcett.com/websketch now!

Ta.