Thursday, August 26, 2010

Working with Arrays in AS3: Part 3

Today we will learn how to remove elements from an Array and how to add elements in the middle of an Array.

There are 3 methods for deleting elements - splice(), pop() and shift(). To remove an element in the middle of the Array - use splice(). Pop() is used to remove the last element, and shift() - the first element.

To destroy elements starting from a specific index use splice() method. There are 2 parameters: start and deleteCount. This first one is the index of the Array's element, at which the removal should start. The second parameter defines how many elements should be removed. If it is undefined - that means all elements starting from the start index will be removed.

var myArray:Array = ["one","two","three","four"];
myArray.splice(1, 1);
trace(myArray);

Output: one, three, four.

The splice() method returns a new Array, that contains the deleted elements.

var myArray:Array = ["one","two","three","four"];
var myNewArray:Array = myArray.splice(0, 2);
trace(myArray);
trace(myNewArray);

Output: three, four and one, two.

To remove the first or the last element use shift() and pop() methods. Note that they not only remove the element, but also return its value. Take a look:

var myArray:Array = ["one","two","three","four"];
// remove the first element and trace its value
trace(myArray.shift());
// remove the last element and trace its value
trace(myArray.pop());
trace(myArray);

Array output: two, three.

The splice() method can remove, but also add new elements to the Array. The values of elements are added after the first 2 parameters of the method. The new elements are added at the start index, and all the existing elements on the right of the index are moved right, to fit in the new elements. If the deleteCount parameter is zero, elements aren't deleted, but the new elements are added.

var myArray:Array= ["one","two","three","four"];
myArray.splice(1, 0, "five", "six", "seven");
trace(myArray);

Output: one, five, six, seven, two, three, four.

You can add and remove elements at the same time:

var myArray:Array= ["one","two","three","four"];
myArray.splice(1, 2, "five", "six", "seven");
trace(myArray);

Output: one, five, six, seven, four.

Which method to use? The one that suits you the best, of course!

Hope this was helpful! Thanks for reading.

Related:

Working with Arrays in AS3: Part 1
Working with Arrays in AS3: Part 2
Working with Arrays in AS3: Part 4
Working with Arrays in AS3: Part 5
Working with Arrays in AS3: Part 6
Working with Arrays in AS3: Part 7

No comments:

Post a Comment