Adding Elements to Arrays


So far we have created an array and placed elements in the array; now lets add elements to an array. There are a couple ways of accomplishing this. Let's start with the simple methods and move into the more dynamic methods.

You can start by setting the length property of an array. Setting the length property of an array will add as many blank elements to that array as you specifybut again, the last blank element will have the index of the length minus 1. Here's an example:

 var my_array:Array = new Array(); my_array.length = 5; trace(my_array); //output: undefined,undefined,undefined,undefined,undefined 

Using the length property to add elements will only add undefined elements to the beginning.

Now we will add elements that actually have data in them. Start by creating an array and adding elements using the index of the elements, as shown here:

 var my_array:Array = new Array("fName","lName"); trace(my_array); my_array [2] = "age"; my_array [3] = "location"; trace(my_array); //output: fName, lName //        fName, lName, age, location 

That was pretty easy. All we did was add elements manually by looking at the next index of the array and assigning an element to it.

Now we will make it more dynamic. Create a button and place it on the main stage. Give it an instance name of "myButton_btn". Then add these actions to the first frame of the main movie:

 var my_array:Array = new Array(); var i:Number = 0; myButton_btn.onPress = function(){        var thisLength:Number = my_array.length;        my_array[thisLength] = i;        i++;        trace(my_array); } //output: (depending on how many times you click the button, increasing //output continued: numbers starting at 0) 

Let's take a look at what we did. First, we created an empty array and a variable that equals zero. Then, we added actions to a button on the main timeline that, when pressed, will set the element with the index of the array's length to the variable i. The variable i will be increased by 1 each time the button is clicked. Finally, we traced the array.

Well, that was pretty dynamic, but we had to write some code that lets us know what the next index of the array should be. Now we're going to talk about an array method that will do the checking for us: the push method.

The push Method

The push method is great when you want to add elements to the end of an array without checking the length. Just call the method on the array using a period and put what you want to add in parentheses following the push. Take a look at the following example:

Start a new Flash document and add these actions to the first frame of the main timeline

 var my_array:Array = new Array(); //create the object to listen for the event var keyListen:Object = new Object(); //create the event keyListen.onKeyDown=function(){         var theKey:String = String.fromCharCode(Key.getAscii());         my_array.push(theKey);         trace(my_array); } //Add the listener Key.addListener(keyListen); //output: (every key you press depending on how many // and which key(s) you press) 

This example is a simple keystroke recorder to show how easily the push method works. It simply "pushes" the keystroke to the end of the array.

NOTE

If, at first, when pressing keys in the test screen, you do not see anything, click the mouse on the stage inside the Flash movie. Even though a keyDown event is occurring, sometimes the mouse must be clicked inside at least once for the event to take place because Flash movies do not always initially receive focus.


You can also push more than one element at a time into an array. In the next example, we will add two pieces of data at the end of the array using the push method:

 var my_array:Array = new Array("fName","lName"); trace(my_array); my_array.push("age","location") trace(my_array); //output: fName, lName //        fName, lName, age, location 

Here, we just added two elements, separated by a comma, to my_array simultaneously using the push method.

You can add any kind of data type using the push method, as shown in the following example:

 var my_array:Array = new Array("fName","lName"); trace(my_array); var x:Number = 10; var another_array:Array = new Array("age","location"); var y:Number = 5 + x; my_array.push(x,y,another_array); trace(my_array); //output: fName, lName //        fName, lName, 10, 15, age, location 

Here, we've added a variable, an expression, and even another array to our original array using the push method.

As an interesting side note to what the push method for arrays can do, you can also check the new length of an array while using the push method to add elements, as shown here:

 var my_array:Array = new Array("fName","lName"); trace(my_array.push("age","location")); trace(my_array); //output: 4 //        fName, lName, age, location 

You can even substitute this method of returning the length for the length property in some cases. Here's an example:

 var my_array:Array = new Array("fName","lName"); trace(my_array.push(my_array.push())); trace(my_array); //output: 3 //        fName, lName, 2 

Because this method adds the number before it checks the length using the push method, it adds the number 2, representing the length of the array, instead of 3.

The push method is great for gathering repetitive information for retrieval. Some examples might be providing back and forward control inside the Flash movie and recording users' information for the next time they visit.

Another example is a search function that searches inside an array and returns the frequency and position of the element you are looking for:

 //First, create the function and label your variables searchArray = function(theArray:Array,lookFor:String) { //Then create an array to hold the positions               var position:Array = new Array();        //Use a for loop statement to check through each element               for (var i:Number = 0; i <=theArray.length-1; i++) {        //Use an if statement to compare each element to what you're looking for                      if (theArray[i] == lookFor) {        //If the element matches, add to the position array                             position.push([i]);                      }               }        //Lastly, trace the results               trace("The frequency is " + position.length);               trace("In position(s) " + position); } var my_array:Array = new Array("fName","lName","age","location","age"); searchArray(my_array,"age"); //output: The frequency is 2 //        In position(s) 2, 4 

This is just another example of how to use the push method and the length property to retrieve elements from an array.

Another method you can use to add elements to an array is the unshift method.

The unshift Method

The unshift method works identically to the push method, except, instead of adding elements to the end, it adds them to the beginning. Here's an example:

 var my_array:Array = new Array("fName","lName"); trace(my_array); my_array.unshift("age"); trace(my_array); //output: fname, lName //        age, fName, lName 

Again, the unshift method adds elements to the beginning of an array. Therefore, each of the original elements' indexes are increased. For instance, fName will go from my_array[0] to my_array[1], and age will become my_array[0].

Also, like the push method, the unshift method can be used to show the length of an array:

 var my_array:Array = new Array("fName","lName"); trace(my_array.unshift("age","location")); trace(my_array); //output: 4 //        age, location, fName, lName 

Like the push method, unshift TRaces the new length and adds elements to the array, but unlike push, it adds them to the front of the array.

The splice Method

The splice method is one of the more powerful methods of arrays. Not only can it add elements to an array, but it can also delete elements and place elements in the middle of arrays. Its syntax is very similar to the other methods we have talked about, except it has multiple parameters:

 my_array.splice(startingIndex,deleteNumber,itemsToAdd); 

Let's take a look at the first part, the part that will delete items from the starting point forward. Attach the method like you would any other, and in the parentheses, place the index of where you want to start deleting items from the array:

 var my_array:Array = new Array("fName","lName","age","location","phone"); my_array.splice(2); trace(my_array); //output: fName, lName 

The method started with the second index, which was age, and deleted all remaining elements. The elements were permanently removed. As a matter of fact, if you check the length of my_array after the splice, the value will be 2.

Now that you know how to delete from one index to the end, let's see how to remove a certain number of elements from a starting point. Use the same code, only this time, in the parentheses place a comma after the starting point and put in however many elements to remove. Here's an example:

 var my_array:Array = new Array("fName","lName","age","location","phone"); my_array.splice(2,2); trace(my_array); //output: fName, lName, phone 

This time the method removed elements from the starting index we assigned and permanently removed the number of elements we assigned. If you check the length, it will return the value 3.

The last step of the splice method is to add elements in the middle of the array, beginning with the starting point. Again, we will be using the same code as before. This time after the number representing the number of elements to remove, we'll place another comma and then add the elements in while separating them with commas:

 var my_array:Array = new Array("fName","lName","age","location","phone"); my_array.splice(2,2,"fax","email"); trace(my_array); //output: fName, lName, fax, email, phone 

This time, the splice method removed the number of assigned elements at the assigned starting point and added elements at the starting point. Again, when adding elements, you can add any type of data, including variables and other arrays.

Now let's add elements to the middle of an array without deleting any elements. This time, we'll use the same syntax but set the number of items we want to delete to zero:

 var my_array:Array = new Array("fName","lName","age","location","phone"); my_array.splice(2,0,"fax","email"); trace(my_array); //output: fName,lName,fax,email,age,location,phone 

Because we set the number of items to delete to zero, the method simply adds the elements in at the index we listed and slides the other elements over.

The splice method has yet another great use. It can return the values of the items removed. Here's an example:

 var my_array:Array = new Array("fName","lName","age","location","phone"); trace(my_array.splice(2,2)); //output: age,location 

In this case, instead of showing what the array looks like after the splice, the method shows what elements were removed. At this point, if you trace the array, it will show the new array with these elements removed. This is really useful if you want to remove certain information from one array and place that information in another array. Here's an example:

 var my_array:Array = new Array("fName","lName","age","location","phone"); var another_array:Array = my_array.splice(2,2); trace(another_array); trace(my_array); //output: age, location //        fName, lName, phone 

This time, we removed items from an array and placed them in a new array called another_array.

You can even add elements to the original array while removing elements from it and placing them into a new array. Using the same code as before, this time we'll add an element to the original array:

 var my_array:Array = new Array("fName","lName","age","location","phone"); var another_array:Array = my_array.splice(2,2,"fax"); trace(another_array); trace(my_array); //output: age, location //        fName,lName,fax,phone 

That was simple enough. We removed two elements and placed them in a new array while adding an element to the original array.

To summarize, the splice method can almost do it all. You can use it to add, remove, and change the elements inside an array. It can even be used to create new arrays.

Another method used for adding elements to arrays is the concat method.

The concat Method

The concat method works similarly to the push method in that it adds elements to the end of an array. However, it does not affect the original array. Instead, it creates a new array with the new elements.

To demonstrate the concat method, let's use our sample array. Now we can create another array by adding elements to the original with the concat method:

 var my_array:Array = new Array("fName","lName","age"); var another_array:Array = my_array.concat("phone","fax"); trace(another_array); //output: fName, lName, age, phone, fax 

The new array, another_array, has both the elements from the original array, my_array, and the new elements we add to the end. If you trace my_array, nothing changes because the concat method only affects the new array it creates.

One nice thing about the concat method is that when adding an array to another array, it separates the elements and adds them as singular elements. Let's take a look at two examples: one using the push method and the other using the concat method.

Here's the example that uses the push() method:

 var my_array:Array = new Array("fName","lName"); var another_array:Array = new Array("age","location"); my_array.push(another_array); trace(my_array [2]); //output: age, location 

And here's the example that uses the concat() method:

 var my_array:Array = new Array("fName","lName"); var another_array:Array = new Array("age","location"); my_array = my_array.concat(another_array); trace(my_array[2]); //output: age 

In the first example, we used the push method to add the second array to my_array. Notice that it doesn't separate the elements into their own individual elements. Instead, it places the entire array in my_array[2]. In the second example, we used the concat method to add the second array to my_array. When the concat method is used, array elements are separated into individual elements.

NOTE

Unless you set the array equal to itself, the concat method will not permanently affect the original array.


Even though concat will separate the elements in an array into individual elements, it will not separate nested arrays. Here's an example:

 var my_array:Array = new Array(["fName","lName"],["age","location"]); var another_array:Array = my_array.concat(my_array); trace(another_array[0]); //output: fName, lName 




Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net