I have an array myArray and a class Thing that I pass it to. I also have a button btn that I click to show the value of myArray.
var myArray:Array= [1,2,3,4,5]
var thing:Thing = new Thing(arr);
btn.addEventListener(MouseEvent:CLICK, traceArray);
function traceArray(m) {trace(myArray)}
Help me understand the behavior shown below. I don’t get why setting arr to [] does nothing but using splice does something.
package {
public class Thing {
public function Thing(arr:Array) {
arr = []; // clicking btn shows 1,2,3,4,5
arr.splice(0, 2); // clicking btn shows 3,4,5
}
}
}
arr = [] changes the variable not the array itself. The arr variable after this line now references a brand new, empty array. The other array still exists - still assigned to myArray outside of the class.
In the case of arr.splice, you’re working from the same array myArray points to, because arr is defined as having the same value as myArray when Thing is called. arr and myArray will be the same unless you change arr to be something else.
This can be tricky to get your head around first. You just gotta mentally get a grasp on where things are defined and how = changes what a variable is and . reaches into a variable and accesses/changes its properties. And when you have an value with properties (objects and arrays), multiple variables can point to the one version of that value.