Skip to main content

Home

Daniel C. Fergus

Artist & Educator

VCB-331 Rich Media 1

Arrays (Flash AS3)

Introduction

An array is a list of items that can be used as variables. Rather than declare each variable separately, we do it all at once with an array. In this exercise we will experiment with a simple array to see how one works.

The Basics

To begin, we'll create an array that contains a list of words. Then we'll use a button to retrieve one of those words from the list.

  1. Open a new Flash file and save it right away as yourName_arrayEx.fla.
  2. On the main timeline create a dynamic text box large enough to hold a single, long word. Give the text box the instance name output_txt.
  3. Create a simple button symbol. Give it the instance name getWord_btn.
  4. Create a new layer and call it actions.
  5. Select the keyframe in the actions layer and open the Actions window. We'll begin the script by declaring and filling our array:
    var myList:Array=new Array("red","orange","yellow","green","blue","purple"); 

    The above syntax is one way you can declare an array. You can also create an array by using an array literal which looks like this:

    var myList:Array=["red","orange","yellow","green","blue","purple"]; 

    Both methods work equally well; the one you use is more or less a matter of preference. Here's another variation that also works:

    var myList:Array=new Array(); 
    // lots of code can go between these lines   
    myList=["red","orange","yellow","green","blue","purple"]; 

    This method allows you to create an empty array with the first line, and then fill it at a later point in the code.

    For now pick one of the above methods to use.

  6. Now add a listener for the button:
    getWord_btn.addEventListener(MouseEvent.CLICK, getWord);  
  7. And now the function called by the button listener:
    function getWord(myEvent:MouseEvent) {
        output_txt.text=myList[3];      
    }    
  8. Try it out. When you hit the button, the word "green" should appear in the text box. But wait a sec—why green? Green is the fourth word, not third, and the function calls the third object in the array, right? Well, not exactly; Flash (and most computer programs) starts counting at zero. Thus, red is word 0, orange is 1, yellow is 2 and green is 3. Confusing? Don't worry, you'll get used to it.

Randomizing the result

Okay that's fine and dandy but all it does whenever I press the button is say "green," what good is that? Well, let's make it a little more interesting by adding a randomizing function.

  1. Add a new button instance and call it random_btn.
  2. Add a new listener for this button:
    random_btn.addEventListener(MouseEvent.CLICK, getRandomWord);
  3. And now the new function:
    function getRandomWord(myEvent:MouseEvent) { 
        var myNumber:Number=Math.round(Math.random()*(myList.length-1));
        output_txt.text=myList[myNumber];      
    }    

    This function first creates a variable called myNumber and then fills it with a random number. The random number is from 1 to the length of myList (which currently is 6 items long). But this will generate a number from 1 to 6, and the array counts from zero to 5, so we have to subtract one from the resulting random number. Then myNumber (which is now a number from 0 to 5) is used to select a word from the array and fill the output text box. try it out.

Getting specific

So what if we want to give the user the ability to choose a number? Let's address that next.

  1. Add a small input text box to the stage, large enough for a 2-digit number. Give the text box the instance name input_txt, and turn on its border so we'll be able to see it when the program runs.
  2. Go back to the getWord function and let's modify it some. The temptation here might be to simply add a line that captures the input number and uses it to grab the corresponding item in the array, something like this:
    var myInput:Number=input_txt.text;    
    output_txt.text=myList[myInput];  

    But this won't work! The problem is a mismatch of variable types. The text box captures string variables and the array uses numbers to count its items. We need to convert the string to a number; there are several easy we can write the conversion, but I prefer a clean two-variable approach:

    function getWord(myEvent:MouseEvent) {
        var myInput:String=input_txt.text; 
        var myNumber:Number=Number(myInput)-1;
        output_txt.text=myList[myNumber];    
    }  

    First I use the variable "myInput" to capture the number input by the user. Next I convert the string to a number (and subtract 1 because arrays count from zero) and place that number in the variable called "myNumber." Finally, I call the item on in the list that corresponds to the number entered by the user.

  3. Okay this works great, as long as the user doesn't enter a number that's too big (or too small), or a letter. We need to add some safeguards to prevent the program from throwing an error if the user does such a silly thing. First let's tackle the issue of numbers that are too big or too small; we'll do this with conditionals:
    function getWord(myEvent:MouseEvent) { 
        var myInput:String=input_txt.text; 
        var myNumber:Number=Number(myInput)-1;        
        if (myNumber>=myList.length) { 
            output_txt.text="Try a smaller number"; 
        }  else if (myNumber< 0) { 
            output_txt.text="Try a bigger number"; 
        } else {
            output_txt.text=myList[myNumber]; 
        }       
    }    
  4. That takes care of numbers that to too big or too small. What if a user types a letter or other character? Let's add another conditional that checks to make sure that the item entered is a number that falls within the proper range:
    function getWord(myEvent:MouseEvent) { 
        var myInput:String=input_txt.text; 
        var myNumber:Number=Number(myInput)-1;        
        if (myNumber>=myList.length) { 
            output_txt.text="Try a smaller number"; 
        }  else if (myNumber< 0) { 
            output_txt.text="Try a bigger number"; 
        } else if (myNumber >= 0 && myNumber < myList.length) {
            output_txt.text=myList[myNumber]; 
        } else { 
            output_txt.text="Type a NUMBER genius!"; 
        }       
    }    

User additions to arrays

Sometimes the data in an array will remain fixed. But other times you might want to give the user to ability to add to (or even remove) items from an array. Let's explore that next.

  1. Add yet another input text field, with a border, large enough to contain a single (long) word. Give the text field the instance name addWord_txt.
  2. Place another button instance on the stage. Let's call this one addWord_btn.
  3. Back to the code. Once again start with a new listener:
    addWord_btn.addEventListener(MouseEvent.CLICK, addWord);    
  4. And now the new function:
    function addWord(myEvent:MouseEvent) { 
        var newWord:String=addWord_txt.text;
        myList.push(newWord);
        addWord_txt.text="";     
    }  
    The push method adds the input item to the end of the list. However there's a potential problem here—if the user hits the addWord button without writing a word, a blank spot will be added to the list. In order to insure that only a legitimate word gets added, let's add a conditional that makes sure the text field is not empty:
  5. Add the lines in black:
    function addWord(myEvent:MouseEvent) { 
        var newWord:String=addWord_txt.text;
        if(newWord!="") {
            myList.push(newWord);
            addWord_txt.text="";  
        }   
    }  
    Try it now.

Removing words from the array

Let's give the user the ability to remove words now.

  1. Add yet another small input text field, large enough to hold a 2-digit number. Give it the instance name cutWord_txt.
  2. And add one more button with the instance name cutWord_btn.
  3. And now add a new listener:
    cutWord_btn.addEventListener(MouseEvent.CLICK, cutWord);  
  4. And a new function:
    function cutWord(myEvent:MouseEvent) { 
        var myInput:String=cutWord_txt.text; 
        var myNumber:Number=Number(myInput)-1;
             
        if (myList.length==0) { 
            output_txt.text="That's all folks"; 
        } else if (myNumber>=myList.length) { 
            output_txt.text="Try a smaller number"; 
        } else if (myNumber< 0) { 
            output_txt.text="Try a bigger number"; 
        } else if (myNumber >= 0 && myNumber < myList.length) {
            myList.splice(myNumber,1); 
            trace(myList); 		
            output_txt.text="";
        } else { 	
            output_txt.text="Type a NUMBER genius!";
        }      
    }    

    This function is very similar to the "getWord" function we wrote above. Like that function, the first few lines capture the text input by the user, and then convert the input text to a number, reducing the number by 1 in the process (since arrays begin counting from 0). Then a series of conditional checks are performed to make sure that the user has chosen a number that will work. The one major difference is found in the last "else if" statement; here we use the splice() method to remove an item from the array. The splice() method takes two arguments—the first is the first item to be removed (whatever number the user enters); the second argument is the number of items removed. Since we're having the user remove one item, we're setting that number to 1.

decorative thumbnail

All text, images, and multimedia pieces (unless otherwise specified) copyright 2005–2011 Daniel C. Fergus. All rights reserved. No reproduction without permission.