Vous êtes sur la page 1sur 14

AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Chapter 6:

Evaluation JavaScript Arrays


1) Introduction.............................................................................................................. 6-2

Copy
2) Creating Arrays ....................................................................................................... 6-3

3) Processing Arrays .................................................................................................... 6-4

4) Array Methods........................................................................................................ 6-6

5) Associative Arrays ................................................................................................. 6-11

Evaluation
Copy
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-1
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Introduction

Evaluation
• An array represents an ordered collection of data, any
element of which can be retrieved by number called its
index.

Copy
 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
arrays, and then we will study how to work with arrays
within the JavaScript.

Copy
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-2
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Creating Arrays

Evaluation
• Since an array is an object (reference data type), creating
one requires use of the new operator and a special
function called a constructor.

Copy
 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);

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

Evaluation
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


Copy
used to determine the number of elements in the array.

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-3
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Processing Arrays

Evaluation
• Arrays are typically processed with for loops to step
through the indices of the array.
 The example below demonstrates various techniques for

Copy
processing arrays.
simpleArrays.js
1. var longNames = new Array(7);
2. longNames[0] = "Sunday";
3. longNames[1] = "Monday";
4. longNames[2] = "Tuesday";
5. longNames[3] = "Wednesday";
6. longNames[4] = "Thursday";
7. longNames[5] = "Friday";
8. longNames[6] = "Saturday";
9.
10. var shortNames = new Array("Sun", "Mon", "Tue",
11. "Wed", "Thu", "Fri", "Sat");
12.
13. var monthNames = ["Jan", "Feb", "Mar", "Apr", "May",
14. "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
15.
16. var days = "31|28|31|30|31|30|31|31|30|31|30|31";
17. var monthDays = days.split("|");
18.
19. var i;
20. document.writeln("<h1>Days of the week:</h1>");
21. for(i = 0; i < longNames.length; i++){
22. document.write(longNames[i] + "&nbsp;");

Evaluation
23. }
24.
25. document.writeln("<hr />");
26. for(i = 0; i < shortNames.length; i++){
27. document.write(shortNames[i] + "&nbsp;");
28. }
29. document.writeln("<hr />");
30.
31.
32.
33.
34.
Copy
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 />");

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-4
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Processing Arrays

Evaluation
• The code from the previous page is referenced in the file
named simpleArrays.html, whose output is shown
below.

Copy

Evaluation
• In addition to the length property of an array, there are
many methods defined for an Array object.

Copy
 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.

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-5
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Array Methods

Evaluation
• Given an array x, the defined methods and syntax for x
are listed below.
 var someArray = x.concat(arg1, arg2, ...);

Copy
• 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

Evaluation
lastElement that it is deleting.

 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

Copy
appending.

 x.reverse();

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

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-6
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Array Methods

Evaluation
• Given an array x, the list of defined methods and syntax
for x are continued below.

Copy
 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
 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

Copy
arguments are inserted in place of the elements being
removed.
• It returns a new array, someArray, of the deleted elements
(if any were deleted).

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-7
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Array Methods

Evaluation
• Given an array x, the list of defined methods and syntax
for x are continued below.

Copy
 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. var x = ["A", "b", "C", "d", "E"];
2. var y = [1, 2, 3, 10, 11, 20, 21, 4, 5, 6];
3. function print(txt){
4. document.write(txt);
5. }
6. function printArrays(txt){

Evaluation
7. print("<dt>" + txt + "</dt>");
8. print("<dd>x = " + x + "</dd>");
9. print("<dd>y = " + y + "</dd>");
10. }
11. print("<dl>");
12. print("<dt>Explicitly calling toString:</dt>");

Copy
13. print("<dd>" + x.toString() + "</dd>");
14. print("<dt>Implicitly calling toString:</dt>");
15. print("<dd>" + x + "</dd>");
16. print("</dl>");
17.

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-8
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Array Methods

18.
19.
20.
Evaluation
arrayMethods.js continued
print("<hr />");
print("<dl>");
printArrays("Before:");

Copy
21. print("<dt class='red'>x.concat(y):</dt>");
22. print("<dd>" + x.concat(y) + "</dd>");
23. printArrays("After:");
24. print("</dl>");
25.
26. print("<hr />");
27. print("<dl>");
28. printArrays("Before:");
29. print("<dt class='red'>x.sort():</dt>");
30. print("<dd>" + x.sort() + "</dd>");
31. print("<dt class='red'>y.sort():</dt>");
32. print("<dd>" + y.sort() + "</dd>");
33. printArrays("After:");
34. print("</dl>");
35.
36. print("<hr />");
37. print("<dl>");
38. printArrays("Before:");
39. print("<dt class='red'>");
40. print("x.splice(2, 2, 'P', 'Q', 'R'):")
41. print("</dt>");
42. print("<dd>");
43. print(x.splice(2, 2, "P", "Q", "R"));
44. print("</dd>");
45. printArrays("After:");
46. print("</dl>");

• The code above is referenced in the file named


Evaluation
arrayMethods.html whose output is shown on the
following page.
 The HTML file also references a CSS style sheet named

Copy
arrayMethods.css to format the output.

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-9
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Array Methods

Evaluation
• The output from arrayMethods.html is shown below.

Copy

Evaluation
Copy
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-10
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Associative Arrays

Evaluation
• Associative arrays are arrays whose element indices are
strings rather than numbers.
 One of the benefits of an associative array is the ability to

Copy
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 Array();
people["Joe"] = "410-555-1234";
people["Sue"] = "410-555-9876";
people["Juan"] = "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
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.

Copy
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.
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-11
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Associative Arrays

2.
3.
Evaluation
statesAndCapitals.js
1. var states = {
"Alabama" : "Montgomery",
"Alaska" : "Juneau",

Copy
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. var currentState = "Maryland";
2. document.write("The capital of " + currentState +
3. " is " + states[currentState] + "<br />");
4. document.write("<table border='1'>");
5. var temp = "<caption>States and Capitals</caption>";
6. document.write(temp);
7. document.write("<thead><tr>");
8. document.write("<th class='key'>State</th>");
9. document.write("<th class='val'>Capital</th>");
10. document.write("<th class='key'>State</th>");
11. document.write("<th class='val'>Capital</th>");
12. document.writeln("</tr></thead>");
13. document.writeln("<tbody>");
14. var column = 0;
15. for (s in states){
16.
17.
18.
19.
20.
Evaluation
if(column % 2 == 0)
document.writeln("<tr>");
document.write("<td class='key'>" + s + "</td>");
document.writeln("<td class='val'>" + states[s] +
"</td>");
21. if(column % 2 == 1)
22.
23.
24.
25.
26.
Copy
}
document.writeln("</tr>");
column++;

document.writeln("</tbody>");
document.writeln("</table>");

©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.


6-12
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Associative Arrays

Evaluation
• The output of associativeArray.html is shown
below.
 The HTML file relies on formatting found in

Copy
associativeArray.css.

Evaluation
Copy
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-13
AJAX - JAVASCRIPT AND XML CHAPTER 6: JAVASCRIPT ARRAYS

Associative Arrays

Evaluation
• The example on the previous page accessed the array by
supplying the key as the index to the array.
document.write(states["Maryland"]);

Copy
• 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
©2011 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
6-14

Vous aimerez peut-être aussi