Arrays
Introduction To Arrays
- The Constructor Method
- The Literal Syntaxt Method
Tutorials
Creating An Array Using the Constructor Method
(See the Video Tutorial)
Introduction:
Arrays are list, and the items in the list are called an elements. Each Element contains an Index and a Value. Indexed Arrays are zero-based, that is, the index for the first item is zero.
Arrays are list, and the items in the list are called an elements. Each Element contains an Index and a Value. Indexed Arrays are zero-based, that is, the index for the first item is zero.
If I were to create an Array whose elements were "Wizard", "Knight", and "Elf" the index value of the "Wizard " would be zero, the "Knight" would be 1 and the "Elf" would be 2.
There are 3 items in this list so the Length of this array is 3.
It's important not to confuse the index value of the last item, which is 2 with the Array Length, which is 3.
Objective:
This tutorial will show you how to create an array.
This tutorial will show you how to create an array.
Like other objects in ActionScript 3, the Constructor method is used to create an instance of the Array object.
In this tutorial, I'll show you how to use the Constructor method to create a new array.
ActionScript:
The Constructor Method looks like this:
The Constructor Method looks like this:
var heroes:Array = new Array();
First, I'm going to declare the name of the variable, which is heroes. I'm going to tell ActionScript what data type. In this case, I want it to be the Array type.
Then I'm going to tell ActionScript to create a new instance that is, a copy of the Array Object.
If I were to test the movie in the Flash Player, I would create an array named, "heroes." However, it would be an empty array because it has no length and it has no elements.
The Constructor method can also be used to Dimension an array, that is, add Length to an array. In this example, I'll show you how to Dimension an array using the Constructor method.
The Constructor Method looks like this:
var heroes:Array = new Array(4);
Here I have set the array's length to 4.
Test The Movie:
If I were to test the movie I would create an Array that has length but no elements.
If I were to test the movie I would create an Array that has length but no elements.
The Constructor method can also be used to Initialize an array, that is, include the initial elements when the array is created.
Objective:
In this example, I'll show you how to Initialize to an array using the Constructor method.
In this example, I'll show you how to Initialize to an array using the Constructor method.
ActionScript:
This time, the constructor method looks like this:
This time, the constructor method looks like this:
var heroes:Array = new Array("Wizard", "Knight", "Elf", "Dwarf");
In this example, I have set the initial elements to:
"Wizard", "Knight", "Elf", "Dwarf"
The quotation marks around each element tell ActionScript that these are String elements. Notice that each element is separated by a comma and there is no comma after the last element.
Test The Movie:
When the movie is tested in the Flash Player, the "Wizard," "Knight," "Elf" and "Dwarf" will appear in the Output Window.
When the movie is tested in the Flash Player, the "Wizard," "Knight," "Elf" and "Dwarf" will appear in the Output Window.
I now have an array that has both length and elements.
--------------------------------------------------------------------------------------------------------
ARRAY PLUS METHOD
--------------------------------------------------------------------------------------------------------
var A :Array = ["A"];
var B :Array = ["B"];
button1.addEventListener(MouseEvent.CLICK, calculate_fn);
function calculate_fn(e:MouseEvent):void {
boxOne.text=String("A"+"B")
}
--------------------------------------------------------------------------------------------------------
TWO ARRAY FUNCTION
1- NEED BUTTON WITH INSTANCE NAME: b_red, b_green, b_yellow, b_blue
2- NEED MOVIE CLIP SYMBOL WITH INSTANCE NAME: sqr
http://coursesweb.net/flash/actionscript-change-movieclip-color_t
--------------------------------------------------------------------------------------------------------
var btts:Array = [b_red, b_green, b_yellow, b_blue];
// sets an object with colors for each button
var set_colors:Object = {'b_red':0xff0000, 'b_green':0x00ff00, 'b_yellow':0xffff00, 'b_blue':0x0000ff};
// sets a ColorTransform object
var obj_color:ColorTransform = new ColorTransform();
// traverse the "btts" array with button instances
for(var i:int=0; i<btts.length; i++) {
// set the color to each button
obj_color.color = set_colors[btts[i].name];
btts[i].transform.colorTransform = obj_color;
// register CLICK event for each button
btts[i].addEventListener(MouseEvent.CLICK, changeColor);
}
// function called by CLICK events
function changeColor(evt:Event):void
{
// get the instance name of the clicked button
var b_name = evt.target.name;
// set and change the square (sqr) color
obj_color.color = set_colors[b_name];
sqr.transform.colorTransform = obj_color;
}
---------------------------------------------------------------------------------------------------
FIND THIS WORD AS3 array of movieclip buttons
http://www.developphp.com/video/Flash/Add-Event-Listeners-to-Object-Groups-Using-a-LoopFIND THIS WORD AS3 array of movieclip buttons
https://www.youtube.com/watch?v=GBMGl05YA_g
---------------------------------------------------------------------------------------------------
var myMenuArray = [home, portfolio, about, services, contact]; for each (var btn in myMenuArray) { btn.addEventListener(MouseEvent.CLICK, onBtnClick); } function onBtnClick (event:MouseEvent):void { pages.gotoAndStop(event.target.name); }
-------------------------------------------------------------------------------------------------
var myClips:Array=new Array(pepper_mc,mushroom_mc,cheese_mc);
myClips.forEach(setAlpha);
function setAlpha(element:*, index:int, array:Array) {
element.alpha=0.5;
}
myClips.forEach(setAlpha);
function setAlpha(element:*, index:int, array:Array) {
element.alpha=0.5;
}
------------------------------------------------------------------------------------------------------------
The Literal Syntaxt Method
-----------------------------------------------------------------------------------------------------------
Tutorials
ActionScript Arrays: Introduction
(See the Video Tutorial)
Objective:
This tutorial will show you how to create an array using the Literal Syntax method.
This tutorial will show you how to create an array using the Literal Syntax method.
The Literal Syntax can be used to create an array and include the initial elements when the array is created.
In this tutorial, I'll show you how to create an array using the Literal Syntax method.
ActionScript:
The Literal Syntax method looks like this:
The Literal Syntax method looks like this:
var heroes:Array = ["Wizard", "Knight", "Elf", "Dwarf"];
Notice that I did not use the term:
= new Array()
The square brackets "[]" tell ActionScript to create a new Array object and fill the array with these elements.
In this case, instancing is implied, and does not have to be explicit.
I'll add a trace statement:
trace(heroes);
Test The Movie:
When the movie is tested, the contents of the "heroes" array will appear in the Output Window.
When the movie is tested, the contents of the "heroes" array will appear in the Output Window.
----------------------------------------------------------------------------------------------------------
- The String() Method
- The toString() Method
- The join() Method
-------------------------------------------------------------------------------------------------------
Tutorials
Displaying Array Elements Using The String() Method
(See the Video Tutorial)
Objective:
This tutorial will show you how to view the contents of an array using the String() method.
This tutorial will show you how to view the contents of an array using the String() method.
Setup:
I'll begin a new ActionScript 3 project. These are my default settings:
Width: 640 px
Height: 480 px
Frame rate: 24.00 fps
Background color: #6699CC
I'll begin a new ActionScript 3 project. These are my default settings:
Width: 640 px
Height: 480 px
Frame rate: 24.00 fps
Background color: #6699CC
You can use whatever color you like. I prefer this neutral color so I can see both black and white text on the stage.
I'll accept these settings and click OK.
Then I'll select my Text Tool I'll leave the default setting at Classic Text but I'll choose Dynamic Text from the drop-down list
I'm selecting Verdana,
Regular
and 16 point for ease of readability.
Regular
and 16 point for ease of readability.
I'll select, "Use device fonts" for Anti-alias. And click the Border Button to show a border around the text.
Now I'll draw a TextField on the stage. I'm going name this TextField, "txtArray" and add some labels.
ActionScript:
I'll open the Actions window. Like I showed you in my previous tutorial I'll use the Literal Syntax method to create an array of Heroes.
I'll open the Actions window. Like I showed you in my previous tutorial I'll use the Literal Syntax method to create an array of Heroes.
var heroes:Array = ["Wizard", "Knight", "Elf", "Dwarf"];
Then I'll assign the Array to the text property of "txtArray," like this:
txtArray.text = heroes;
"txtArray" is the TextField
text is a property of the TextField
'equals' is the Assignment Operator
and heroes is the Array
text is a property of the TextField
'equals' is the Assignment Operator
and heroes is the Array
Test The Movie:
If I were to test this movie, I would get an error message. That's because heroes is still an Array. I need to convert heroes to a String so it can be displayed in the TextField.
If I were to test this movie, I would get an error message. That's because heroes is still an Array. I need to convert heroes to a String so it can be displayed in the TextField.
Objective:
The String() method is used convert the value of any object into a string of characters. In this example, I'll show you how to use the String Method to convert an Array Object into a string.
The String() method is used convert the value of any object into a string of characters. In this example, I'll show you how to use the String Method to convert an Array Object into a string.
This time, I'll assign a string value to the text property of "txtArray"
txtArray.text = String(heroes);
String is the method and heroes is the Array Object will be converted to a string.
Test The Movie:
Now when the movie is tested, the array of Heroes will be displayed in the txtArray TextField.
Now when the movie is tested, the array of Heroes will be displayed in the txtArray TextField.
var heroes:Array = ["Wizard", "Knight", "Elf", "Dwarf"]; txtArray.text = String(heroes);
----------------------------------------------------------------------------------------------------------
Tutorials
Displaying Array Elements Using The toString() Method
(See the Video Tutorial)
Objective:
This tutorial will show you how to view the contents of an array using the String() method.
This tutorial will show you how to view the contents of an array using the String() method.
The toString() method is actually part of the Interger Class but works perfectly well with Arrays. In this example, I'll show you how to convert an Array to a String using the toString() method.
ActionScript:
The toString code looks like this:
The toString code looks like this:
txtArray.text = heroes.toString();
heroes is the Array and toString() is the method.
Test The Movie:
When the movie is tested, the array of Heroes will be displayed in the txtArray TextField, identical to the String() method.
When the movie is tested, the array of Heroes will be displayed in the txtArray TextField, identical to the String() method.
var heroes:Array = ["Wizard", "Knight", "Elf", "Dwarf"]; txtArray.text = heroes.toString();
-----------------------------------------------------------------------------------
Tutorials
Displaying Array Elements Using The join() Method(See the Video Tutorial)Objective: This tutorial will show you how to view the contents of an array using the join() method.The join() method is used to replace the comma separator with another character or word before it converts the array to a string. In this example, I'll show you how to use the join() method to replace comma separator in my heroes array.ActionScript: First, I'll declare a variable to hold the contents of the array:var strHeroes:String;strHeroes is the name of my variable and String is the data typeThe join method looks like this:strHeroes = heroes.join(" -> ");strHeroes is the variable 'equals' is the Assignment Operator heroes is the Array join is the method and these are the characters I will use to replace the commas.Then I'll assign strHeroes to the text property of "txtArray"txtArray.text = strHeroes;Test The Movie: When the movie is tested, you should see that the element separators are now little arrows.Examples The join() Method (See the Video Tutorial) (See the Written Tutorial) The join() method not only converts an array object to a string but it allows you to insert your own separator. In this example, I'll replace the comma seperator with arrows. In the first line of code below, the Literal Syntax method is used to create an array of heroes. The second line of code creates a variable named, strHeroes. The third line of code extracts the elements from the heroes array using the join() method, adds the "->" separator and assigns the result to the strHeroes variable. The forth line of code then assigns the contents of the strHeroes to the text property of the txtArray TextField. ActionScript var heroes:Array = ["Wizard", "Knight", "Elf", "Dwarf"]; var strHeroes:String; strHeroes = heroes.join(" -> "); txtArray.text = strHeroes; ---------------------------------------------------------------------------------------- Accessing Individual Array Elements The Array Access Operator
Tutorials
Using The Array Access Operator
(See the Video Tutorial)
Objective:
In this tutorial, I'll show you how to make your Flash Movies more interactive. I'll start with the project I used to illustrate the String() method.
In this tutorial, I'll show you how to make your Flash Movies more interactive. I'll start with the project I used to illustrate the String() method.
Setup:
From the Window menu, I'll select Common Libraries from the drop-down list. I'll click on Buttons.
From the Window menu, I'll select Common Libraries from the drop-down list. I'll click on Buttons.
I like the push buttons so I'll scroll down to classic buttons expand the folder and scroll down to find Push Buttons.
Then I'll drag the buttons into the Name section in my Library and close the Window.
I'll create a new layer and call it Buttons. In this layer, I'll drag the green button to the stage and name it "btnGreen" and add a label.
ActionScript:
I'll open my Actions panel and create a function to respond to a button click event.
I'll open my Actions panel and create a function to respond to a button click event.
I'll call my function, showHeroes
Notice when I selected MouseEvent ActionScript automatically added an Import Statement for the MouseEvent:
function showHeroes(event:MouseEvent):void
I'll cut the String method and paste it into this function:
txtArray.text = String(heroes);
Then I'll add the button listener:
btnGreen.addEventListener(MouseEvent.CLICK, showHeroes);
"btnGreen" is the name of the button,
addEventListener is the name of the method.
addEventListener is the name of the method.
When the listener method detects a Mouse Click it will execute the showHeroes function.
Objective:
The array access operator is used to access an individual element in an array. In this example, I'll show you to use the array access operator to display one of my Heroes in a TextField.
The array access operator is used to access an individual element in an array. In this example, I'll show you to use the array access operator to display one of my Heroes in a TextField.
Setup:
I'm going to start with my previous project.
I'm going to start with my previous project.
I'll drag an Orange button to the stage, and name it "btnOrange".
Then I'll copy my dynamic TextField paste it in the center. I'll name it, txtElement.
Then I'll resize the TextField and add a label.
The array access operator looks like this:
heroes[0]
"heroes" is the name of the array and [0] is the index number for the element that I wish to retrieve.
I'll copy my previous function and paste it here.
I'll re-name the function, "showElement," change the button to btnOrange, and change the function call to "showElement"
Inside this function, I'll change the TextField name to "txtElement." and place my array access operator inside the String function.
When you click on the Green button in this example, you will see an array of heroes.
When you click on the Orange button, you will see the first element in this array - element[0]
In the code below, the showHeroes function displays the array contents in the first TextField.
The showElement function displays the first array element in the second TextField.
function showHeroes(event:MouseEvent):void
{
txtArray.text = String(heroes);
}
btnGreen.addEventListener(MouseEvent.CLICK, showHeroes);
function showElement(event:MouseEvent):void
{
txtElement.text = String(heroes[0]);
}
btnOrange.addEventListener(MouseEvent.CLICK, showElement);
----------------------------------------------------------------------------------------------------
Creating An Array Of Objects
Using the Constructor Method
Position Array MovieClip Elements on the Stage
Tutorials
How To Create An Array of Movie Clip Objects
(See the Video Tutorial)
Objective:
In this tutorial, I'll show you how to create an array of MovieClip objects.
Setup:
I've already created some images to use in my role playing game and I've converted those images to Movie Clips. Now I'll transfer these Movie Clips to a new ActionScript 3 project.
I'll open the Library for my source files and copy all the Movie Clips, including assets and paste them into the Name Section of the Library for the New Project.
Before I can use ActionScript to load the Movie Clips, I'll need to modify them.
I'll select my Wizard and view his properties.
Under ActionScript Linkage, I'll check the boxes:
Export for ActionScript and
Export in frame 1
I'll do this for the rest of my Heroes and for the rest of my Evil-Doers.
ActionScript:
In ActionScript 3, a Movie Clip is an Object. And like any other object, I'll use the Constructor Method to create a new Wizard Object.
I'll open my Actions Panel.
The Constructor Method looks like this:
var objWizard:wizard = new wizard;
objWizard is the Variable Name.
Wizard is the data type.
Equals is the Assignment Operator
and New Wizard indicates that I'll be creating a New Instance of the Wizard Movie Clip.
Now I need to place this Object into a Container such as the Stage or another Movie Clip. This container will be the Parent and the Object will be the Child.
I'll use the Add Child Method to add the Wizard to the Stage:
stage.addChild(objWizard);
Stage is the Parent
addChild is the Method
and objWizard is the child object to be added to the stage.
Since the code is written to a layer on the Stage, ActionScript assumes we mean the Stage to be the Parent. So this shortcut is perfectly acceptable:
addChild(objWizard);
Test The Movie:
If I tested the movie now, The Wizard Movie Clip would be loaded to the stage but not necessarily where I want him to be.
Objective:
I'll use the Movie Clip's X and Y properties to position my Wizard.
I have set the registration point for all of my Movie Clips at the front and bottom of each character's near foot. This way, all of my characters will be standing on the same plane regardless of their height.
I'll position my Wizard on the stage, like this:
objWizard.x = 120;
objWizard.y = 250;
The Wizard's foot will align at X = 120 pixels and Y = 250 pixels.
Test The Movie:
Now when I test the movie the Wizard will be standing exactly where I want him to.
addChild(objWizard);
objWizard.x = 120;
objWizard.y = 250;
Tutorials
How To Display An Array of MovieClip Objects
(See the Video Tutorial)
Objective:
In this tutorial, I'll show you how to create an array of MovieClip objects and how to position each MovieClip on the stage using the Array Access Operator.
In this tutorial, I'll show you how to create an array of MovieClip objects and how to position each MovieClip on the stage using the Array Access Operator.
First, I'll add the rest of my heroes using the Constructor method.
var objWizard:wizard = new wizard;
var objKnight:knight = new knight;
var objElf:elf = new elf;
var objDwarf:dwarf = new dwarf;
var objWizard:wizard = new wizard;
var objKnight:knight = new knight;
var objElf:elf = new elf;
var objDwarf:dwarf = new dwarf;
Then I'll add the rest of my Hero Children.
addChild(objWizard);
addChild(objKnight);
addChild(objElf);
addChild(objDwarf);
addChild(objKnight);
addChild(objElf);
addChild(objDwarf);
My array of MovieClip objects looks like this:
var heroes:Array = [objWizard, objKnight, objElf, objDwarf];
I am not using quotation marks because these elements are Objects, and not Strings.
Finally, I'll place each MovieClip object on the stage, like this:
heroes[0].x = 120;
heroes[0].y = 250;
heroes[1].x = 260;
heroes[1].y = 250;
heroes[0].y = 250;
heroes[1].x = 260;
heroes[1].y = 250;
The first element in the "heroes" array has an index value of zero and this is my Wizard.
Test The Movie:
Now when I test the movie, all my Hero MovieClips have be loaded onto the stage.
Now when I test the movie, all my Hero MovieClips have be loaded onto the stage.
var objWizard:wizard = new wizard;
var objKnight:knight = new knight;
var objElf:elf = new elf;
var objDwarf:dwarf = new dwarf;
addChild(objWizard);
addChild(objKnight);
addChild(objElf);
addChild(objDwarf);
var heroes:Array = [objWizard, objKnight, objElf, objDwarf];
heroes[0].x = 120;
heroes[0].y = 250;
heroes[1].x = 260;
heroes[1].y = 250;
heroes[2].x = 400;
heroes[2].y = 250;
heroes[3].x = 540;
heroes[3].y = 250;
--------------------------------------------------------------------------------------------------------
Combining Arrays
Using the concat() Method
https://www.youtube.com/watch?v=5U991eavSRI&feature=youtu.be
Tutorials
Combining Arrays Using The concat() Method
(See the Video Tutorial)
Objective:
In this tutorial, I'll show you how to combine arrays and how to use arrays to position MovieClip objects on the stage. In my first example, I'll show you how to combine arrays using the concat() method.
ActionScript:
Like I did with my "heroes" array, I'll use the Constructor method to create my "evil" MovieClip objects:
var objWarlock:warlock = new warlock;
var objDemon:demon = new demon;
var objOgre:ogre = new ogre;
var objGoblin:goblin = new goblin;
Then I'll add my Evil Children:
addChild(objWarlock);
addChild(objDemon);
addChild(objOgre);
addChild(objGoblin);
And create an array of Evil-Doers:
var evils:Array = [objGoblin,objOgre,objDemon,objWarlock];
I now have 2 Arrays.
I'm going to combine these 2 arrays using the array concat() method. My code looks like this:
var characters:Array = heroes.concat(evils);
Characters will be my new Array
Heroes is my First Array
Concat is the Method
and Evils is my Second Array.
Finally, I'll add the X and Y coordinates for all the characters:
characters[0].x = 120;
characters[0].y = 200;
characters[0].y = 250;
characters[1].x = 260;
characters[1].y = 250;
... and so on.
Test The Movie:
When the movie is tested, all the MovieClips in the characters array have been placed on the Stage.
Examples
Combining Arrays
(See the Video Tutorial)
(See the Written Tutorial)
In this example, an array of hero movie clip objects and an array of evil-doer movie clip objects are created. Then both arrays are combined into one characters array using the concat() method.
Finally, each element (movie clip) is identified by the "array access operator" and positioned on the stage according to the values assigned to the object's X and Y properties.
var objWizard:wizard = new wizard; var objKnight:knight = new knight; var objElf:elf = new elf; var objDwarf:dwarf = new dwarf; var objWarlock:warlock = new warlock; var objDemon:demon = new demon; var objOgre:ogre = new ogre; var objGoblin:goblin = new goblin; addChild(objWizard); addChild(objKnight); addChild(objElf); addChild(objDwarf); addChild(objWarlock); addChild(objDemon); addChild(objOgre); addChild(objGoblin); var heroes:Array = [objWizard, objKnight, objElf, objDwarf]; var evils:Array = [objGoblin,objOgre,objDemon,objWarlock]; var characters:Array = heroes.concat(evils); characters[0].x = 120; characters[0].y = 250; characters[1].x = 260; characters[1].y = 250; characters[2].x = 400; characters[2].y = 250; characters[3].x = 540; characters[3].y = 250; characters[4].x = 90; characters[4].y = 440; characters[5].x = 230; characters[5].y = 440; characters[6].x = 370; characters[6].y = 440; characters[7].x = 510; characters[7].y = 440;
--------------------------------------------------------------------------------------------
Using X and Y Arrays to Position Array Elements
https://www.youtube.com/watch?v=5U991eavSRI&feature=youtu.be
Objective:
In this example, I'm going to create Two New Arrays to help me place my characters.
In this example, I'm going to create Two New Arrays to help me place my characters.
ActionScript:
I'm going to create an array of X values and another array of Y values. My arrays look like this:
I'm going to create an array of X values and another array of Y values. My arrays look like this:
var X:Array = [120,260,400,540,90,230,370,510];
var Y:Array = [250,250,250,250,440,440,440,440];
var Y:Array = [250,250,250,250,440,440,440,440];
There are no quotation marks around each element because each element is a mumber.
Then I'm going to create a function to place my characters. I'll call this function, "placeCharacters"
function placeCharacters():void
In this function, I'm going to create a For-Loop:
for (var i:int = 0; i < characters.length; ++i)
The For-Loop requires 3 expressions:
A variable set to an initial value , which I've set to Zero,
A Conditional Statement (loop as long as i is less than the characters.length)
And an change value, which I've set to Increment by One.
A variable set to an initial value , which I've set to Zero,
A Conditional Statement (loop as long as i is less than the characters.length)
And an change value, which I've set to Increment by One.
The reason why I say less than, instead of equal to is because the array's length is 8 but the index for the last element is 7.
Then I'll position each character, like this:
characters[i].x = X[i];
characters[i].y = Y[i];
characters[i].y = Y[i];
Now, each element in the characters array corresponds to each element in the X and Y Arrays.
Finally, I'll call my function using this statement:
placeCharacters();
Test The Movie:
If all goes well, the characters should appear in the same place as they did in the previous example.
If all goes well, the characters should appear in the same place as they did in the previous example.
var objWizard:wizard = new wizard; var objKnight:knight = new knight; var objElf:elf = new elf; var objDwarf:dwarf = new dwarf; var objWarlock:warlock = new warlock; var objDemon:demon = new demon; var objOgre:ogre = new ogre; var objGoblin:goblin = new goblin; addChild(objWizard); addChild(objKnight); addChild(objElf); addChild(objDwarf); addChild(objWarlock); addChild(objDemon); addChild(objOgre); addChild(objGoblin); var heroes:Array = [objWizard, objKnight, objElf, objDwarf]; var evils:Array = [objGoblin,objOgre,objDemon,objWarlock]; var characters:Array = heroes.concat(evils); var X:Array = [120,260,400,540,90,230,370,510]; var Y:Array = [250,250,250,250,440,440,440,440]; for (var i:int = 0; i < characters.length; ++i) { characters[i].x = X[i]; characters[i].y = Y[i]; }
--------------------------------------------------------------------------------------------------------------------
- Adding Elements to an Array
- The push() Method
- The unshift() Method
- The splice() Method
- The Assignment Operator
Tutorials
Adding Array Elements Using The push() Method
Objective:
In this tutorial, I'll show you various methods that allow you to add elements to an Array. I'll begin by showing you the push() method.
In this tutorial, I'll show you various methods that allow you to add elements to an Array. I'll begin by showing you the push() method.
Setup:
I'm going to start with the last example I used in my previous tutorial. I have already added a graphic to the stage. This will be the backdrop for my role playing characters.
I'm going to start with the last example I used in my previous tutorial. I have already added a graphic to the stage. This will be the backdrop for my role playing characters.
In order to fit my characters on this backdrop, I've reduced their size by 50 percent. I have also added a green button to the stage, which I've named, "btnGreen".
ActionScript:
Next, I'll modify my code. I'm going to delete all the previous Arrays:
Next, I'll modify my code. I'm going to delete all the previous Arrays:
var heroes:Array = [objWizard, objKnight, ...];
var evils:Array = [objGoblin, objOgre, ...];
var characters:Array = heroes.concat(evils)
And create a new empty Array:
var characters:Array = new Array();
Then I'll modify the X and Y Arrays to position my characters on top of the backdrop:
var X:Array = [80,150,220,290,360,430,500,570];
var Y:Array = [120,120,120,120,120,120,120,120];
I'm going to create a new function called, "pushElement":
function pushElement(event:MouseEvent):void
{
characters.push(objWarlock);
}
{
characters.push(objWarlock);
}
"characters" is the name of the Array;
"push" is the Method;
and "objWarlock" is the MovieClip object to be added after the last element in the array.
"push" is the Method;
and "objWarlock" is the MovieClip object to be added after the last element in the array.
Then I'm going to cut and paste the placeCharcters call inside this new function:
placeCharacters();
Finally, I'll add a button listener:
btnGreen.addEventListener(MouseEvent.CLICK, pushElement);
Test The Movie:
Although the Warlock is the only character in this array, it's important to remember that the push() method adds a new element after the last element.
Although the Warlock is the only character in this array, it's important to remember that the push() method adds a new element after the last element.
Examples
Adding Elements To An Array
(See the Video Tutorial)
(See the Written Tutorial)
(See the Written Tutorial)
In this example, the constructor method is used to create copies of the 8 character movie clip objects.
Then the addChild() method is used to add all the child objects to the container (stage).
Next, an empty characters array is created using the constructor method.
Next, 2 more arrays are created, an X array containing the X values and a Y array containing the Y values.
When you click the green button, the push() method is used to add theobjWarlock movie clip to the next open position in the characters array.
When you click the orange button, the unshift() method is used to insert theobjWizard movie clip to position 0 in the characters array.
When you click the blue button, the splice() method is used to insert theobjKnight, objElf and objDwarf movie clips starting at position 1, right after objWizard which is located at position 0 in the characters array.
When you click the red button, the assignment operator is used to move theobjDwarf movie clip to position 0 and then move the objWizard movie clip to position 3 in the characters array.
import flash.events.MouseEvent;var objWizard:wizard = new wizard;
var objKnight:knight = new knight;
var objElf:elf = new elf;
var objDwarf:dwarf = new dwarf;
var objWarlock:warlock = new warlock;
var objDemon:demon = new demon;
var objOgre:ogre = new ogre;
var objGoblin:goblin = new goblin;
addChild(objWizard);
addChild(objKnight);
addChild(objElf);
addChild(objDwarf);
addChild(objWarlock);
addChild(objDemon);
addChild(objOgre);
addChild(objGoblin);
var characters:Array = new Array();
var X:Array = new Array(80,150,220,290,360,430,500,570);
var Y:Array = new Array(120,120,120,120,120,120,120,120);
function pushElement(event:MouseEvent):void
{
characters.push(objWarlock);
placeCharacters();
btnGreen.removeEventListener(MouseEvent.CLICK, pushElement);
}
btnGreen.addEventListener(MouseEvent.CLICK, pushElement);
function unshiftElement(event:MouseEvent):void
{
characters.unshift(objWizard);
placeCharacters();
btnOrange.removeEventListener(MouseEvent.CLICK, unshiftElement);
btnBlue.addEventListener(MouseEvent.CLICK, spliceElements);
}
btnOrange.addEventListener(MouseEvent.CLICK, unshiftElement);
function spliceElements(event:MouseEvent):void
{
characters.splice(1, 0, objKnight, objElf, objDwarf);
placeCharacters();
btnBlue.removeEventListener(MouseEvent.CLICK, spliceElements);
btnRed.addEventListener(MouseEvent.CLICK, swapElements);
}
function swapElements(event:MouseEvent):void
{
characters[0] = objDwarf;
characters[3] = objWizard;
placeCharacters();
btnRed.removeEventListener(MouseEvent.CLICK, swapElements);
}
function reset(event:MouseEvent):void
{
hideCharacters();
characters.length = 0;
btnGreen.addEventListener(MouseEvent.CLICK, pushElement);
btnOrange.addEventListener(MouseEvent.CLICK, unshiftElement);
btnBlue.removeEventListener(MouseEvent.CLICK, spliceElements);
btnRed.removeEventListener(MouseEvent.CLICK, swapElements);
}
btnYellow.addEventListener(MouseEvent.CLICK, reset);
function placeCharacters():void
{
for (var i:int = 0; i < characters.length; ++i)
{
characters[i].x = X[i];
characters[i].y = Y[i];
characters[i].visible = true;
}
}
function hideCharacters():void
{
for (var i:int = 0; i < characters.length; ++i)
{
characters[i].visible = false;
}
}
-----------------------------------------------------------------------------------------------------------------
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
https://jsfiddle.net/fmjL1eyL/
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fa4.html
-----------------------------------------------------------------------------------------------------------------
Sorting an array
There are three methods— reverse() , sort() , and sortOn() —that allow you to change the order of an indexed array, either by sorting or reversing the order. All of these methods modify the existing array. The following table summarizes these methods and their behavior for Array and Vector objects:
Method
|
Array behavior
|
Vector behavior
|
---|---|---|
reverse()
|
Changes the order of the elements so that the last element becomes the first element, the penultimate element becomes the second, and so on
|
Identical to Array behavior
|
sort()
|
Allows you to sort the Array’s elements in a variety of predefined ways, such as alphabetical or numeric order. You can also specify a custom sorting algorithm.
|
Sorts the elements according to the custom sorting algorithm that you specify
|
sortOn()
|
Allows you to sort objects that have one or more common properties, specifying the property or properties to use as the sort keys
|
Not available in the Vector class
|
The reverse() method
The reverse() method takes no parameters and does not return a value, but allows you to toggle the order of your array from its current state to the reverse order. The following example reverses the order of the oceans listed in the oceans array:
var oceans:Array = ["Arctic", "Atlantic", "Indian", "Pacific"]; oceans.reverse(); trace(oceans); // output: Pacific,Indian,Atlantic,Arctic
Basic sorting with the sort() method (Array class only)
For an Array instance, the sort() method rearranges the elements in an array using the default sort order . The default sort order has the following characteristics:
- The sort is case-sensitive, which means that uppercase characters precede lowercase characters. For example, the letter D precedes the letter b.
- The sort is ascending, which means that lower character codes (such as A) precede higher character codes (such as B).
- The sort places identical values adjacent to each other but in no particular order.
- The sort is string-based, which means that elements are converted to strings before they are compared (for example, 10 precedes 3 because the string "1" has a lower character code than the string "3" has).
You may find that you need to sort your Array without regard to case, or in descending order, or perhaps your array contains numbers that you want to sort numerically instead of alphabetically. The Array class’s sort() method has an options parameter that allows you to alter each characteristic of the default sort order. The options are defined by a set of static constants in the Array class, as shown in the following list:
- Array.CASEINSENSITIVE : This option makes the sort disregard case. For example, the lowercase letter b precedes the uppercase letter D.
- Array.DESCENDING: This reverses the default ascending sort. For example, the letter B precedes the letter A.
- Array.UNIQUESORT: This causes the sort to abort if two identical values are found.
- Array.NUMERIC: This causes numerical sorting, so that 3 precedes 10.
The following example highlights some of these options. An Array named poets is created that is sorted using several different options.
var poets:Array = ["Blake", "cummings", "Angelou", "Dante"]; poets.sort(); // default sort trace(poets); // output: Angelou,Blake,Dante,cummings poets.sort(Array.CASEINSENSITIVE); trace(poets); // output: Angelou,Blake,cummings,Dante poets.sort(Array.DESCENDING); trace(poets); // output: cummings,Dante,Blake,Angelou poets.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options trace(poets); // output: Dante,cummings,Blake,Angelou
Custom sorting with the sort() method (Array and Vector classes)
In addition to the basic sorting that’s available for an Array object, you can also define a custom sorting rule. This technique is the only form of the sort() method that is available for the Vector class. To define a custom sort, you write a custom sort function and pass it as an argument to the sort() method.
For example, if you have a list of names in which each list element contains a person’s full name, but you want to sort the list by last name, you must use a custom sort function to parse each element and use the last name in the sort function. The following code shows how this can be done with a custom function that is used as a parameter to the Array.sort() method:
var names:Array = new Array("John Q. Smith", "Jane Doe", "Mike Jones"); function orderLastName(a, b):int { var lastName:RegExp = /\b\S+$/; var name1 = a.match(lastName); var name2 = b.match(lastName); if (name1 < name2) { return -1; } else if (name1 > name2) { return 1; } else { return 0; } } trace(names); // output: John Q. Smith,Jane Doe,Mike Jones names.sort(orderLastName); trace(names); // output: Jane Doe,Mike Jones,John Q. Smith
The custom sort function orderLastName() uses a regular expression to extract the last name from each element to use for the comparison operation. The function identifier orderLastName is used as the sole parameter when calling the sort() method on the names array. The sort function accepts two parameters, a and b , because it works on two array elements at a time. The sort function’s return value indicates how the elements should be sorted:
- A return value of -1 indicates that the first parameter, a , precedes the second parameter, b .
- A return value of 1 indicates that the second parameter, b , precedes the first, a .
- A return value of 0 indicates that the elements have equal sorting precedence.
The sortOn() method (Array class only)
The sortOn() method is designed for Array objects with elements that contain objects. These objects are expected to have at least one common property that can be used as the sort key. The use of the sortOn() method for arrays of any other type yields unexpected results.
Note: The Vector class does not include a sortOn() method. This method is only available for Array objects.
The following example revises the poets Array so that each element is an object instead of a string. Each object holds both the poet’s last name and year of birth.
var poets:Array = new Array(); poets.push({name:"Angelou", born:"1928"}); poets.push({name:"Blake", born:"1757"}); poets.push({name:"cummings", born:"1894"}); poets.push({name:"Dante", born:"1265"}); poets.push({name:"Wang", born:"701"});
You can use the sortOn() method to sort the Array by the born property. The sortOn() method defines two parameters, fieldName and options . The fieldName argument must be specified as a string. In the following example, sortOn() is called with two arguments, " born" and Array.NUMERIC . The Array.NUMERIC argument is used to ensure that the sort is done numerically instead of alphabetically. This is a good practice even when all the numbers have the same number of digits because it ensures that the sort will continue to behave as expected if a number with fewer or more digits is later added to the array.
poets.sortOn("born", Array.NUMERIC); for (var i:int = 0; i < poets.length; ++i) { trace(poets[i].name, poets[i].born); } /* output: Wang 701 Dante 1265 Blake 1757 cummings 1894 Angelou 1928 */
Sorting without modifying the original array (Array class only)
Generally, the sort() and sortOn() methods modify an Array. If you wish to sort an Array without modifying the existing array, pass the Array.RETURNINDEXEDARRAY constant as part of the options parameter. This option directs the methods to return a new Array that reflects the sort and to leave the original Array unmodified. The Array returned by the methods is a simple Array of index numbers that reflects the new sort order and does not contain any elements from the original Array. For example, to sort the poets Array by birth year without modifying the Array, include the Array.RETURNINDEXEDARRAY constant as part of the argument passed for the options parameter.
The following example stores the returned index information in an Array named indices and uses the indices array in conjunction with the unmodified poets array to output the poets in order of birth year:
var indices:Array; indices = poets.sortOn("born", Array.NUMERIC | Array.RETURNINDEXEDARRAY); for (var i:int = 0; i < indices.length; ++i) { var index:int = indices[i]; trace(poets[index].name, poets[index].born); } /* output: Wang 701 Dante 1265 Blake 1757 cummings 1894 Angelou 1928 */
EmoticonEmoticon