Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Lecture 2

Array allows storing and accessing elements by index. Elements can be added, removed, or iterated over. Arrays have properties like length and methods like push(), pop(), splice(), slice(), indexOf(), and sort() to modify and work with elements. Arrays can be sorted by properties of complex elements using sortOn().

Uploaded by

Nirmal Ramessur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 2

Array allows storing and accessing elements by index. Elements can be added, removed, or iterated over. Arrays have properties like length and methods like push(), pop(), splice(), slice(), indexOf(), and sort() to modify and work with elements. Arrays can be sorted by properties of complex elements using sortOn().

Uploaded by

Nirmal Ramessur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Web Multimedia

programming
Lecture 2: Arrays

1
Array Basics
• Arrays are like a numbered list of items where each item, or element, in an array
has a location, or index. Indices in an array start at 0 instead of 1. These indices
are used to look up elements in the array.
Using the Array Constructor to create an array
1. var myArray:Array = new Array();
• To visualize an array, think of a set of numbered cubbyholes, each containing a
single item.
• If you want to create an array and assign values to it at the same time, just pass
those values to the constructor:
2. var myThings:Array = new Array("coffee filters", "stapler", "Spin Doctors CD");
• Arrays in ActionScript can contain any type of object or even disparate types.
These are called mixed arrays.
• The third form of the Array constructor allows you to specify the new array’s
initial length.
3. var topTen:Array = new Array(10); // creates an array with 10 spaces
• In practice, this ability is not useful. An array’s length is dynamic and changes to fit
your needs for it
2
Array Basics
• Creating an Array by Using an Array Literal
• To write an array literal, list the contents of the array separated by
commas and surround the whole thing in a set of square brackets ([]).
For example:[1,2,3]
• The previous code is equivalent to this: new Array(1, 2, 3);
• As you can see, the literal form is more compact. Let’s assign an array
literal to a variable:
4. var fibonacci:Array = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
• Likewise, you can create a new empty array by using an empty array
literal:
var a:Array = [];

3
Array Basics
• Referencing Values in an Array
• An array’s values are stored in indices. Each index is numbered
starting from 0 and counting up to one less than the length of the
array.
• To look up a value in an array, you’ll use the array variable followed
by the array access operator ([]) containing the index you want.
var animals:Array = ["newt", "vole", "cobra", "tortoise"];
trace(animals[2]); //cobra
• By writing animals[2], you’re asking for the item stored at index 2 in
the array. An indexed position in an array is no different from a
variable with a name:
animals[0] = "salamander";
trace(animals); //salamander,vole,cobra,tortoise
4
Array Basics
• Finding the Number of Items in an Array
• Check the length property of the array,

5
Array Basics
• Converting Arrays to Strings
• The toString() method is implicitly called when you use an array where a
string is expected. You have already been using this with trace(), which
prints out its arguments. Array’s toString() method renders it as a
comma-separated list of values.
var names:Array = ["Jenene", "Josh", "Jac"];
trace(names); //Jenene,Josh,Jac

• The Array class provides another way to display its values as a string. By
using the join() method, you can provide your own delimiter to separate
the array’s contents:
var menu:Array = ["eggplant parmesan", "chocolate", "fish tacos"];
trace("For dinner we’re having " + menu.join(" and ") + ". Yum!");
• //For dinner we’re having eggplant parmesan and chocolate and fish tacos.
Yum!
• Here the commas are replaced by the word ‘‘and,’’ making the sentence
read a little more naturally
6
Adding and Removing Items from an Array
• The Array class provides methods for adding items to and removing
items from your array without regard for their index numbers. This
enables you to collect objects in a list without a care and to use your
array as a stack or a queue.

Notice that the original arrays, a and b, remain unchanged during this operation. The
concat()method is nondestructive: it returns a new array that is based on the original
but doesn’t affect the original array.
7
Applying Stack Operations push() and pop()
• A stack is a list of data that is maintained
in a first in, last out (FILO) manner. In
other words, the first thing that goes in
is the last thing that comes out.
• Values can be pushed onto the end of
an array using push() and popped off
the end using pop().
• The push() method takes one or more
objects as parameters and adds
them all in order to the end of the
array. The pop() method, conversely,
takes no arguments. It removes and
returns the last element of the array.
8
Slicing and Splicing
• Inserting and Removing Values with splice()
• The splice() method takes two required parameters: the starting index,
which is where the insertion or deletion will begin, and the delete count,
which is the number of elements you want to delete from the array (0 if
you want to insert only).
• You may also add any number of optional parameters, which are elements
that will be added to the array at the start index. If any elements are
removed from the array, they’re returned by the splice() method.
• Let’s look at splice() in action:
var nobleGasses:Array = ["helium", "neon", "argon", "pentagon", "xenon", "radon"];
var shapes:Array = nobleGasses.splice(3, 1, "krypton");
//delete 1 element at index 3, and replace it with "krypton".
trace(nobleGasses); //helium,neon,argon,krypton,xenon,radon
trace(shapes); //pentagon 9
Working with a Subset of your Array with slice()
• To extract a subset of your array to work on independently of the original
array, you can use the slice() method. Slicing works pretty much the same
way for the Array class. Just specify the start and end index (not inclusive)
of the slice you want to create.
• Collected Snippets: Slicing an Array
var metals:Array = ["iron", "copper", "gold", "silver", "platinum", "tin", "chrome"];
var preciousMetals:Array = metals.slice(2,5);
trace(preciousMetals); //gold,silver,platinum
• The slice()method also accepts negative numbers, which count from the
end of the array rather than the beginning.
var metals:Array = ["iron", "copper", "gold", "silver", "platinum", "tin", "chrome"];
var canMakingMetal:Array = metals.slice(-2,-1);
trace(canMakingMetal); //tin
10
Iterating through the Items in an Array
• Using a for Loop
for (var i:int = 0; i < menuItems.length; i++) {
trace(menuItems[i]);
}

• Using for each..in


• This loop was made for arrays! When using a for each..in loop, you don’t
have to keep track of any loop variables, or even access the values of the
array by index.
for each (var menuItem:String in menuItems) {
trace(menuItem);
}
• This loop is cleaner and less prone to errors. If you don’t care about indices,
for example if you’re using your array as a list, this method of looping is
desirable.
11
Searching for Elements
• Search an array for any value using the indexOf() and lastIndexOf()
methods. The methods return the index in the array that contains the
specified element.
var cats:Array = ["Cheetah", "Puma", "Jaguar", "Panther", "Tiger", "Leopard"];
trace(cats.indexOf("Leopard")); //5
trace(cats.indexOf("Ocelot")); //-1 meaning that the value is not found
• lastIndexOf() ???

12
Reordering Your Array
• Using Sorting Functions
• The Array class has two methods for sorting contents: sort() and
sortOn().
• Example: sort() will sort the array alphabetically
var fruits:Array= ["peach", "Apple", "orange"]
trace(fruits.sort()); //Apple, orange, peach

• Notice that the sort() method is destructive: it makes changes to the


array directly.

13
sortOn()
• 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.
• Note: The Vector class does not include a sortOn() method. This
method is only available for Array objects.
• 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"});
14
sortOn()
• 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
*/

15
Flipping the Order of an Array Using Reverse()
• Reverse means flip the order so that the last is first and vice versa. To
do this, use the reverse() method on your array:
var myArray:Array = [12,6,17,4,39];
myArray.reverse();
trace(myArray); //39,4,17,6,12
• This reorders the contents within the array on which it is called
without creating a new array.

16
Multidimensional Arrays
• With a multidimensional array you can store values using two or more nested
indices, which allow you to create data sets within data sets.
• Creating a multidimensional array means to simply create an array as one of the
elements of another array:
var grid:Array = new Array(new Array(1,2), new Array(3,4));
//or var grid:Array = [[1, 2], [3, 4]];
trace(grid[0][0]); //1
trace(grid[0][1]); //2
trace(grid[1][0]); //3
trace(grid[1][1]); //4
• An expression like grid[0][1] has two implicit steps. grid[0] retrieves the first index
in the outer array. You find that this, too, is an array and [1] retrieves the second
item in the inner array.
• Suppose you want to store information in two dimensions — such as the locations
of the pieces on a chessboard. Well, a chessboard is 8 squares wide by 8 squares
high, so it’s 8 × 8. To store all the values for this board, you would need 8 arrays,
each with a length of 8. Using a two-dimensional array, you could store this 2D
grid-like data in one array. The next example sets up a new chessboard by
creating several arrays within one array. 17
A Chessboard as a Two-Dimensional Array
const k:String = "King";
const q:String = "Queen"; • The example will display:

const b:String = "Bishop"; • Piece at (0,2) : Bishop

const n:String = "Knight"; • Piece at (7,4) : King


• Piece at (4,3) : empty
const r:String = "Rook";
• Piece at (7,7) : Rook
const p:String = "Pawn";
const _:String = "empty";
var chessBoard:Array = [
[r,n,b,q,k,b,n,r],
[p,p,p,p,p,p,p,p],
[_,_,_,_,_,_,_,_],
[_,_,_,_,_,_,_,_],
[_,_,_,_,_,_,_,_],
[_,_,_,_,_,_,_,_],
[p,p,p,p,p,p,p,p],
[r,n,b,q,k,b,n,r]
];
trace("Piece at (0,2) :", chessBoard[0][2]);
trace("Piece at (7,4) :", chessBoard[7][4]);
trace("Piece at (4,3) :", chessBoard[4][3]);
trace("Piece at (7,7) :", chessBoard[7][7]);
18
Amazing Properties of Arrays
• Arrays are dynamically sized. You never have to do anything to
allocate more memory for them or free memory they’re not using.
• Arrays are always mutable. You can always create, remove, update,
and delete values from them.
• Arrays are mixed. You can put multiple types into an array, even if
they’re not the same type.
• Arrays can be sparse, meaning that you can have a gap in the indices
of an array.
var arr:Array = ["zero", "one", "two"];
arr[5] = "five";
trace(arr); //zero,one,two,,,five

19
Practical 1
1. Declare an array using the both methods learnt in class that contains the following elements:
Milk, Eggs, sausage, cereal, juice.
2. Write the codes to:
1. Display the array
2. Display the length of the array
3. Add the element “bread” using index and push methods.
4. Create a new array based on the original array and add two more elements in it using the concat() method.
3. Reverse the array and display it by using “and” delimeter
4. Display the array by using for loop and for each …in loop
5. Remove the last element of the array.
6. Remove sausage and replace it with salmon. (Use splice method)
7. Add elements tea and toast starting at index 3 using splice method
8. Create a new array using slice method that contains only the second, third and fourth element
9. Search for element Coffee in the original array and display a message if found or not
10. Sort the original array and display it

20
Practical 2
• Create four separate arrays containing values for first name, last
name and year born.
• Create a new array that will hold the four arrays defined above.
• Display the newly created array on separate lines.

21

You might also like