If you have ever created an array in ActionScript or any other ECMAScript based programming language, creating an Array in JavaScript will be very familiar to you. On the other hand, if you are an array noob, you are certainly not alone. Arrays are a sticking point for many new programmers, but alas, salvation is neigh! Allow me to walk you through the creation of a simple JavaScript array, that, for the most part, can also be used in ActionScript.
What is an Array?
An array, at its simplest, is really nothing more than a collection of items that is assigned as a variable. When an item is added to the array, it is given a number called an index. The item can then be referenced later by calling the array variable along with the index number of the item you want to access. Clear as mud? Great! Let’s see an example.
How do I Create an Array?
My wife is making tacos tonight, so I will use my hunger as inspiration.
Awesome, we just created a delicious array!
- The first step in creating an array is to declare a variable for it. In this case the variable I want to use is ingredients.
- The second step is to cast the variable as an Array object. Some people would argue that this step isn’t necessary, and they’re correct, but it is a best practice to type cast your variables as often as possible.
- The third step is to add items to your array. The easiest way to do that is to set your array variable (in this case ingredients) equal to a bracket enclosed, comma delineated list of items. In my case I added three strings to the ingredients array.
- The final step isn’t really needed, but is allows you to see what your array looks like at this point. You will see all three comma delineated strings, Beans, Meat, and Cheese in the alert box. This is normal and just means that the array contains all three of those items.
Now, say you’re a meatetarian… How do you only select the one item of the array that you want? It’s actually as easy as grabbing the meat spoon!… so to speak. You just need to call the name of the array variable with the index of the item you want added in brackets (E.g: ingredients[1]).
There is one important thing you should know about indexes in ECMAScript based languages: counting always starts at 0… I don’t know why the rule exists, I just follow it. The first item in your array will always be index 0 (ingredients[0] = Beans in this case), followed by 1, 2, 3 and so on.
This should be enough to help you get started working with Arrays. Check back soon for more on Arrays including some Intermediate and Advanced Array techniques.