Tuesday, August 24, 2010

Working with Arrays in AS3: Part 1

In this tutorial you will learn how to create Arrays and add elements to it.

Arrays are very commonly used in all programming languages. The idea behind it is simple. An array is an arrangement of elements. Imagine that you have a shopping list with products that you need to buy. Each product is an element of the shopping list array.

Creating arrays couldn't be more simple.

var myArray:Array = new Array();
// Creates an empty array

var myArray2:Array = new Array(element1, element2, element 3);
// Creates an array with 3 elments in it

var myArray3:Array = ["one", "two", "three"];
// Creates an array with 3 elements in it

You can access and set array's elements through the [ ] operator and an index of the element.

myArray[3]="test"
// The fourth element is now "test"

trace(myArray[3]);
// Output: test

It should be noted that the first element of an Array has an index of 0, the second - 1, third - 2 and so on. That's why we are actually accessing the 4th element when we write myArray[3].

Actionscript doesn't care which type are the elements in an array. You can even make an Array of Arrays. You can create an Array that contains different typed elements, for example, a string, a boolean and a number:

var myArray:Array = ["hello", true, 31];

You can add elements to an Array using the push() and unshift() methods. Push() adds an element in the end of the Array, and unshift() adds an element in the beginning.

var myArray:Array = new Array("hello");
myArray.push("hey","hi");

// Array: ["hello","hey","hi"]

var myArray2:Array = new Array("hello");
myArray2.unshift("hey","hi");

// Array: ["hey","hi","hello"]

If you try to create an element with a not-existing index, the Array extends and fills the empty space with undefined elements.

var myArray:Array = [1, 2, 3];
myArray[5] = 4

// Array: [1, 2, 3, undefined, undefined, 4]

Arrays have a property called length, which represent, you guessed it, the total number of elements in the Array. This means we have another way of adding elements in the end of the Array:

var myArray:Array = [1, 2, 3];
myArray[myArray.length] = 4

// Array: [1, 2, 3, 4]

These are the basics. Thanks for reading!

Related:

Working with Arrays in AS3: Part 2
Working with Arrays in AS3: Part 3
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