3 Replies Latest reply on May 20, 2009 5:13 PM by kglad

# Can somebody please explain me this logic?

array = [1,2,3,4,5,6,7];

newArray = array;
trace ("array: " + array);

newArray = newArray.splice (0, 5);
trace ("array: " + array);

Output:

array: 1,2,3,4,5,6,7
array: 6,7

As you can see, I set a variable equal to another (newArray = array), then splice it. But the problem is, it is affecting the old variable too!

How can that be?

I need to use the complete original "array", but no matter how many variables I create equal to it, when I splice them, it affects all of them!

I might find a solution by turning the variable into string, then back to array or something like that. But what I would like is to understand what's going on in that code. If someone could explain me, i'd appreciate it a lot.

• ###### 1. Re: Can somebody please explain me this logic?

because they both point to the same object.  (if you don't understand how pointers work, search using google until you understand.)

to copy an array, change the copy and NOT have hit change the original, use slice():

var copyA:Array = oldA.slice();

now, any changes to copyA will leave oldA unchanged.

• ###### 2. Re: Can somebody please explain me this logic?

Thank you.

That helped me out.

I found my problem also in the Flash Documentation. I couldn't find it before because i didn't know what to look for.

Anyway, here's the link if someone wants it:

It teaches how to create a copy of an array using a "for", but "kglad's" method is much better.

• ###### 3. Re: Can somebody please explain me this logic?

you're welcome.