00:00
00:00
Newgrounds Background Image Theme

Limaou just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

As3: Arrays, Vectors & Dictionaries

13,142 Views | 4 Replies
New Topic Respond to this Topic

AS3: Arrays, Vectors & Dictionaries
----------------------
AS3: Main
----------------------
Prerequisite reading: None
----------------------
Source file(s): N/A
----------------------

As your applications grow in size you're likely to have more & more objects on your display list and more data to work with and managing everything can become tricky. Rather than trying to reference each object individually by name it is much cleaner and quicker to store them in a list.

In AS3 there are three types of "list" object: Array, Vector and Dictionary. All three allow you to store references to other objects or values so that you can access them later.

Array

Arrays are the simplest and most used way of storing a collection of data. They are initialised the same way as any other object. The Array constructor takes an optional parameter that defines its size:

//creates empty array
var a:Array = new Array();

//creates an array 5 elements long
var b:Array = new Array(5);

If more than one parameter is passed to the Array constructor the array is populated with those elements:

//creates an array with 2 elements; "Hello" & "World"
var c:Array = new Array("Hello", "World");

There are no restrictions to what you can store in an Array:

var num:Number = 5;
var mc:MovieClip = new MovieClip();
var array:Array = new Array(mc, num, "Hello", false, 42);

Every element inside the array is assigned an index. This is zero based, so the first element in the array is 0 not 1. We can read & write to a certain element by using the square bracket notation:

//creates an array 5 elements long
var array:Array = new Array(5);

//set the fifth element to "Hello World"
array[4] = "Hello World";

//Output:  "Hello World"
trace(array[4]);

Note how the fifth element is referenced by the number 4. Again this is because the indexes start at 0. It's also worth mentioning that Arrays are sparse arrays, meaning, unlike Vectors, they can have empty elements. In the above example tracing array[0] would return undefined.

You can even insert an array into an array to create multi-directional arrays. This is handy if you're building a board game, or tile map for example. Multi-directional arrays are referenced using the same square bracket notation:

var array:Array = new Array(5);

//add a new array to the first element of array
array[0] = new Array(5);

//set the fifth element of the array at array[0] to "Foo Bar"
array[0][4] = "Foo Bar";
trace(array[0][4]);

There are a number of properties and methods on array objects that can help you do some pretty cool things. For an in-depth look the properties/methods please consult the official documentation. Below is a cursory overview of some key features:

length - returns the length of the array

indexOf - returns the position of the search term. It returns -1 the search term does not exist.
Example:

var array:Array = new Array(5);
array[4] = "Hello World";, 

//Output: 4
trace(array.indexOf("Hello World"));

//Output: -1
trace(array.indexOf("Hello"));

push - adds one or more elements to the end of the array.

splice - removes (and adds) elements to an array. This method takes three parameters: startIndex, deleteCount and values. startCount is the index from which to start deleting from and deleteCount is the number of elements to remove. values is an optional parameter. Anything passed here will be inserted into the position defined in startIndex.

forEach - calls the specified function for each item in the array.
Example:

var array:Array = new Array(1, 2, 3, 4, 5);
array.forEach(showElement);

function showElement(element:*, index:int, arr:Array):void {
		trace(element);
}

It is important to note that the call back function (in this example showElement requires 3 paramaters: element, which the current element in the array, index, which is the position of said element, and arr, which the current array calling forEach.

This is not the only way to iterate through arrays however. For example, you could also use for loops or a for... in statement:

var array:Array = new Array(1, 2, 3, 4, 5);

for (var i:int = 0; i < array.length; i++) {
	trace(array[i]);
}
			
for each(var j:* in array) {
	trace(j);
}

Vector

For all intents are purposes Vectors are essentially typed arrays. They are declared slightly different to most other objects:

var vector:Vector.<String> =  new Vector.<String>();

The above example declares a new Vector of type String. This means you can only store strings in this vector. Vectors can be of any type, even your own custom classes:

var nunVector:Vector.<Number> =  new Vector.<Number>();
var customVector:Vector.<MyCustomClass> =  new Vector.<MyCustomClass>();

Again, like Array you can pass an optional size parameter to the Vector constructor. However, Vectors are dense arrays, so where as empty elements in Arrays would be undefined, in a Vector they are null.

var nunVector:Vector.<String> =  new Vector.<String>(5);

//Output: null
trace(nunVector[4])

Like Arrays, you can have a Vector of type Vector, essentially creating a multi-dimensional Vector. While the apparent draw back of Vectors is that, unlike Arrays, they are restricted to storing only one type, the benefit is that they are considerably faster at iteration and individual element access.

N.B. At the time of writing however, it should be noted that when exporting to Air for iOS Vectors are actually slower than Arrays.

A lot of the methods found on Array are also found on Vector. A detailed explanation of all the methods and properties is beyond the scope of this article, so I would direct you once again to the documentation.

Dictionary

While Arrays & Vectors use numbers for references, a Dictionary object uses Keys.

Here we create a new Dictionary, a new MovieClip and use that MovieClip as a key in our Dictionary:

var dict:Dictionary = new Dictionary();
var mc1:MovieClip = new MovieClip();
dict[mc1] = "Hello World";

//Output: Hello World
trace(dict[mc1]);

Aside from objects, you can also use primitives, like you would with an array:

var dict:Dictionary = new Dictionary();
dict[1] = "Foo Bar";

//output: Foo Bar;
trace(dict[1]);

To remove an association in a dictionary, you use the delete keyword:

var dict:Dictionary = new Dictionary();
dict[1] = "Foo Bar";
delete dict[1];		

//Output: undefined
trace(dict[1]);

For more information on the Dictionary object check out the documentation.

As you can see Arrays, Vectors & Dictionaries provide an easy and powerful way to store and manipulate information. Their uses are many, and are a vital tool to help keep your content manageable.


The water in Majorca don't taste like what it oughta.

| AS3: Main | AS2: Main | Flash Tutorials |

BBS Signature

Response to As3: Arrays, Vectors & Dictionaries 2012-03-19 21:01:39


Arrays and vectors also have alternate and faster methods of being set.

// [ ] creates a new instance of an array
var a:Array = [1,2,3];

//Vector.<T> is also a global function which takes an Array as its parameters.  The contents of that Array must still be the type you choose for the Vector
var v:Vector.<int> = Vector.<int>( [1,2,3] );

Response to As3: Arrays, Vectors & Dictionaries 2012-03-21 15:45:18


As you can see Arrays, Vectors & Dictionaries provide an easy and powerful way to store and manipulate information. Their uses are many, and are a vital tool to help keep your content manageable.

How do you know which to use? Can you rank them on resource usage?

Response to As3: Arrays, Vectors & Dictionaries 2012-03-21 15:54:19


At 2 minutes ago, DavidHan wrote: How do you know which to use? Can you rank them on resource usage?

Depends on what you're doing with the data that is in the container.
Examples:

Arrays should be used when you are storing more than one type, or are allocating Object types.
Vectors should be used when you are only storing a single type, you want a fixed-length container, or if you are allocating base types (i.e. int, uint, Number, Boolean and String).
Dictionaries should be used if you are not iterating through the container, but instead using index values to look-up elements.

Resource wise an Array uses the least, and a Dictionary uses the most.
Though you don't need to concern yourself with that; it's negligible in AS3.

Response to As3: Arrays, Vectors & Dictionaries 2012-03-21 17:03:36


I read somewhere that adobe is planning on supporting typed arrays, this would be a good improvement.