Você está na página 1de 14

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Chapter 6:
JavaScript Arrays

1) Introduction.............................................................................................................. 6-2
2) Creating Arrays ....................................................................................................... 6-3
3) Processing Arrays .................................................................................................... 6-4
4) Array Methods........................................................................................................ 6-6
5) Associative Arrays ................................................................................................. 6-11

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-1

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Introduction

An array represents an ordered collection of data, any

element of which can be retrieved by number called its


index.
 Array indices start at 0; therefore an array of 5 elements would
have indices of 0, 1, 2, 3, and 4.

 The number of elements in an array can be changed at any


time.

A value is retrieved from an array by enclosing the index


inside a set of square brackets.

 For example, if an array is named item and pos is an integer:


item[pos] is an element of the array; and
item[3] references the fourth element of the item array.

An array in JavaScript may contain any data type or


combination of data types.

Arrays are reference data types and as such behave


differently than primitive data types.

We will first study the various techniques for creating new

Evaluation
Copy

arrays, and then we will study how to work with arrays


within the JavaScript.

2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-2

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Creating Arrays

Since an array is an object (reference data type), creating


one requires use of the new operator and a special
function called a constructor.
 For an array, the name of its constructor is Array.

The Array constructor can be invoked in several different


ways.

 One way is to invoke the constructor with no parameters,


creating a new array object with no elements.
var a = new Array();
 Another way is to pass a comma separated list of arguments to
the constructor, creating a new array object and initializing it
with the supplied values.
var a = new Array(5, 10, 15, 20);
 Another way is to pass a single number to the constructor,
creating a new array object with that number of elements, each
of whose value is the special undefined value.
var a = new Array(10);

Evaluation
Copy

 The final way is to use a literal array by placing a comma


separated list of values inside a set of square brackets.

var a = ["Mon", "Tue", "Wed", "Thu", "Fri"];

Once an array is created, its length property can be

used to determine the number of elements in the array.

2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-3

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Processing Arrays

Arrays are typically processed with for loops to step


through the indices of the array.

 The example below demonstrates various techniques for


processing arrays.
simpleArrays.js
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.

var longNames = new Array(7);


longNames[0] = "Sunday";
longNames[1] = "Monday";
longNames[2] = "Tuesday";
longNames[3] = "Wednesday";
longNames[4] = "Thursday";
longNames[5] = "Friday";
longNames[6] = "Saturday";
var shortNames = new Array("Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat");
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = "31|28|31|30|31|30|31|31|30|31|30|31";
var monthDays = days.split("|");
var i;
document.writeln("<h1>Days of the week:</h1>");
for(i = 0; i < longNames.length; i++){
document.write(longNames[i] + "&nbsp;");
}

Evaluation
Copy

document.writeln("<hr />");
for(i = 0; i < shortNames.length; i++){
document.write(shortNames[i] + "&nbsp;");
}
document.writeln("<hr />");
document.writeln("<h1>Months of the year:</h1>");
for(i = 0; i < monthNames.length; i++){
document.write(monthNames[i] + " has ");
document.writeln(monthDays[i] + " days<br />");
}

2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-4

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Processing Arrays

The code from the previous page is referenced in the file


named simpleArrays.html, whose output is shown
below.

Evaluation
Copy

In addition to the length property of an array, there are


many methods defined for an Array object.

 Methods are different from functions, in that a method is called


on an instance of an object, whereas a function is not.
 More details of methods will be discussed in the chapter
covering the object-oriented aspect of JavaScript.
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-5

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Array Methods

Given an array x, the defined methods and syntax for x


are listed below.

 var someArray = x.concat(arg1, arg2, ...);

It returns a new array, someArray, which is the result of


concatenating the arg(s), passed as arguments to the
method, to x.

If one of the arguments being passed is itself an array, its


elements are concatenated, rather than the array itself.
The method does not modify the original array x.
 var someString = x.join(separator);
It returns a string someString that is the result of
converting each element of array x to a string and
concatenating it.
An optional separator string can be passed as an
argument, which would be inserted between each string
being concatenated to someString.
 var lastElement = x.pop();
It modifies the array x by deleting the last element,
decrementing its length by one, and returns the element
lastElement that it is deleting.

Evaluation
Copy

 var lastElement = x.push(arg1, arg2, ...);

It modifies the array x by appending the arg(s) to the end


of x and returns the element lastElement that it is
appending.

 x.reverse();

Modifies the array x by reversing the order if its elements.


2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-6

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Array Methods

Given an array x, the list of defined methods and syntax


for x are continued below.

 var firstElement = x.shift();

It modifies the array x by deleting the first element of x.


The index of each element in x is shifted down by one and
the length of x is decremented by one.

It returns the firstElement of the array x that is being


deleted.
 var someArray = x.slice(start, end);
It returns a new array someArray that is a subset from
start up to but not including end.
If the end is not specified, the subset is from start to the
end of the array.
 x.sort();
It modifies the array x by sorting in ascending alphabetical
order.
Elements of the array are first converted to strings if
necessary.

Evaluation
Copy

 var someArray = x.splice(s, cnt, v1, v2,...);


It modifies the array x by starting at s, and deleting cnt
number of elements.

If optional arguments are supplied (v1, v2, ...), the


arguments are inserted in place of the elements being
removed.

It returns a new array, someArray, of the deleted elements


(if any were deleted).

2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-7

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Array Methods

Given an array x, the list of defined methods and syntax


for x are continued below.

 var someString = x.toString();

It converts array x to a string by first converting each


element of x to a string and returning a comma separated list
of all the strings as one string.

 var someString = x.unshift(arg1, arg2, ...);


It modifies the array x by inserting the arg(s) at the
beginning of the array.

The example below demonstrates several of the methods


that can be called on an Array.

 The example defines two print functions to simplify the use of


document.write().
arrayMethods.js
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

var x = ["A", "b", "C", "d", "E"];


var y = [1, 2, 3, 10, 11, 20, 21, 4, 5, 6];
function print(txt){
document.write(txt);
}
function printArrays(txt){
print("<dt>" + txt + "</dt>");
print("<dd>x = " + x + "</dd>");
print("<dd>y = " + y + "</dd>");
}
print("<dl>");
print("<dt>Explicitly calling toString:</dt>");
print("<dd>" + x.toString() + "</dd>");
print("<dt>Implicitly calling toString:</dt>");
print("<dd>" + x + "</dd>");
print("</dl>");

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-8

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Array Methods

arrayMethods.js continued
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.

print("<hr />");
print("<dl>");
printArrays("Before:");
print("<dt class='red'>x.concat(y):</dt>");
print("<dd>" + x.concat(y) + "</dd>");
printArrays("After:");
print("</dl>");
print("<hr />");
print("<dl>");
printArrays("Before:");
print("<dt class='red'>x.sort():</dt>");
print("<dd>" + x.sort() + "</dd>");
print("<dt class='red'>y.sort():</dt>");
print("<dd>" + y.sort() + "</dd>");
printArrays("After:");
print("</dl>");
print("<hr />");
print("<dl>");
printArrays("Before:");
print("<dt class='red'>");
print("x.splice(2, 2, 'P', 'Q', 'R'):")
print("</dt>");
print("<dd>");
print(x.splice(2, 2, "P", "Q", "R"));
print("</dd>");
printArrays("After:");
print("</dl>");

Evaluation
Copy

The code above is referenced in the file named

arrayMethods.html whose output is shown on the


following page.
 The HTML file also references a CSS style sheet named
arrayMethods.css to format the output.

2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-9

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Array Methods

The output from arrayMethods.html is shown below.

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-10

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Associative Arrays

Associative arrays are arrays whose element indices are


strings rather than numbers.

 One of the benefits of an associative array is the ability to


retrieve its data without the cost of searching the array.
 An associative array can be thought of as a collection of
key/value pairs, where the key is unique within the array.
The keys act as the indices into the array, and each is
associated with a value.

The code below associates people's names (keys) with


their phone numbers (values).
var people = new
people["Joe"] =
people["Sue"] =
people["Juan"] =

Array();
"410-555-1234";
"410-555-9876";
"410-555-5678";

The same array could also be initialized using the


following shorthand notation.

var people = {"Joe" : "410-555-1234",


"Sue" : "410-555-9876",
"Juan" : "410-555-5678"};

There is an additional looping construct in JavaScript,

Evaluation
Copy

often referred to as a for/in loop.

 While not restricted to associative arrays as far as its use, the


for/in loop is often used with associative arrays.
 The general syntax of a for/in loop is shown below.
for(variable in object)
statement(s);

The example on the next page demonstrates the use of


associative arrays to deal with states and their capitals.
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-11

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Associative Arrays

statesAndCapitals.js

1. var states = {
2.
"Alabama" : "Montgomery",
3.
"Alaska" : "Juneau",
4.
.
5.
.
6.
.
7.
"Wisconsin" : "Madison",
8.
"Wyoming" : "Cheyenne"
9. };

 The above data is a snippet of the full 50 states and capitals


defined in the actual file.
associatveArray.js
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

var currentState = "Maryland";


document.write("The capital of " + currentState +
" is " + states[currentState] + "<br />");
document.write("<table border='1'>");
var temp = "<caption>States and Capitals</caption>";
document.write(temp);
document.write("<thead><tr>");
document.write("<th class='key'>State</th>");
document.write("<th class='val'>Capital</th>");
document.write("<th class='key'>State</th>");
document.write("<th class='val'>Capital</th>");
document.writeln("</tr></thead>");
document.writeln("<tbody>");
var column = 0;
for (s in states){
if(column % 2 == 0)
document.writeln("<tr>");
document.write("<td class='key'>" + s + "</td>");
document.writeln("<td class='val'>" + states[s] +
"</td>");
if(column % 2 == 1)
document.writeln("</tr>");
column++;
}
document.writeln("</tbody>");
document.writeln("</table>");

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-12

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Associative Arrays

The output of associativeArray.html is shown


below.

 The HTML file relies on formatting found in


associativeArray.css.

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-13

AJAX - JAVASCRIPT AND XML

CHAPTER 6: JAVASCRIPT ARRAYS

Evaluation
Copy
Associative Arrays

The example on the previous page accessed the array by


supplying the key as the index to the array.
document.write(states["Maryland"]);

Another way is to access the value as a property of the


array, where the property name is the key.
document.write(states.Maryland);
 This technique will be discussed in more detail in chapter
pertaining to the object-oriented aspect of JavaScript.

Evaluation
Copy
2007 /training/etc Inc.

REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-14

Você também pode gostar