Advertisement |
Adding Elements to the Array
Once you created your array you would probably have to add more elements to it later in the project. There are a number of ways for doing this. The easiest one is done using the square brackets []. Using the square brackets, you can add any value at the specific index you set. For example, if we want to add a new element at index 3 in our array we do it this way:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray[3] = "Tutorial";
trace(myArray);
myArray[3] = "Tutorial";
trace(myArray);
Testing this code should output the following: "Flash,ActionScript,Republic of Code,Tutorial".
The code above would add your element to index 3. You should be cautious when using this method because you could accidentally overwrite your new content over old elements if that index is already occupied. For example, if you put the value Tutorials in index 2 instead of 3 this would overwrite the value Republic of Code:
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray[2] = "Tutorial";trace(myArray);
myArray[2] = "Tutorial";trace(myArray);
Testing this code should output the following: "Flash,ActionScript,Tutorial".
Attempting to add your new elements at an index further than the current length of your array would also generate empty slots in the array to fill all these unused indexes.
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray[6] = "Tutorial";trace(myArray);
myArray[6] = "Tutorial";trace(myArray);
Testing this code should output the following: "Flash,ActionScript,Republic of Code, , , ,Tutorial".
Instead of attempting to use the square brackets to add an item to your array, you can alternatively use the push() method to add an item automatically to the end of your array. This way you do not have to know the current number of items in your list.
var myArray:Array = ["Flash", "ActionScript", "Republic of Code"];
myArray.push("Tutorials");trace(myArray);
myArray.push("Tutorials");trace(myArray);
Testing this code should output the following: "Flash,ActionScript,Republic of Code,Tutorial".
The square brackets technique and the push() method could be helpful in different circumstances depending on the nature and needs of your project.
0 comments: