1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 25 ppsx

15 289 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 15
Dung lượng 1,52 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

It calls the Array object’s constructor func-tion, Array, to create a new Array object.. var array_name = new Array100; And in the following example, a dense array is given a list of in

Trang 1

213

chapter

9

JavaScript

Core Objects

9.1 What Are Core Objects?

Like an apple, JavaScript has a core, and at its core are objects Everything you do in

JavaScript will be based on objects; you may create your own as we did in Chapter 8,

“Objects,” or use JavaScript’s core objects Core objects are built right into the language

JavaScript provides built-in objects that deal with the date and time, math, strings,

reg-ular expressions, numbers, and other useful entities The good news is that the core

objects are consistent across different implementations and platforms and were

stan-dardized by the ECMAScript 1.0 specification, allowing programs to be portable

Although each object has a set of properties and methods that further define it, this book

does not detail every one, but highlights those that will be used most often For a

com-plete list of properties and objects, go to http://www.echoecho.com/jsquickref.htm.

9.2 Array Objects

An array is a collection of like values—called elements—such as an array of colors,

an array of strings, or an array of images Each element of the array is accessed with an

index value enclosed in square brackets (see Figure 9.1) An index is also called a

sub-script There are two types of index values: a nonnegative integer and a string Arrays

indexed by numbers are called numeric arrays and arrays indexed by strings are called

associative arrays (see Figure 9.2) In JavaScript, arrays are built-in objects with some

added functionality

Figure 9.1 A numeric Array object called color Index values are numbers.

Trang 2

9.2.1 Declaring and Populating Arrays

Like variables, arrays must be declared

before they can be used Let’s examine

some ways to create an array

Creating an Array Object with

new. The new keyword is used to

dynamically create the Array object It

calls the Array object’s constructor

func-tion, Array(), to create a new Array

object The size of the array can be

passed as an argument to the constructor,

but it is not necessary Values can also be

assigned to the array when it is

con-structed, called a dense array, but this is

not required either The following array

is called array_name and its size is not

specified

In the next example, the size or length of the array is passed as an argument to the

Array() constructor The new array has 100 undefined elements

var array_name = new Array(100);

And in the following example, a dense array is given a list of initial values at the same

time it is being declared:

var weekday = new Array("Sunday", "Monday", "Tuesday");

Figure 9.2 An associative Array object called hex Index values are strings.

F O RM A T

var array_name = new Array();

Example:

var months = new Array();

months[0]="January";

months[1]="February";

months[2]="March"

“#FF0000” “#0000FF” “#00FF00”

hex[“red”] hex[“blue”] hex[“green”]

Trang 3

The values can be of any data type or combination of types Although you can specify

the size of the array when declaring it, it is not required JavaScript allocates memory as

needed to allow the array to shrink and grow on demand To populate the array, each

element is assigned a value Each element is indexed by either a number or string If the

array index is a number, it starts with 0 JavaScript doesn’t care what you store in the

array Any combination of types, such as numbers, strings, Booleans, and so forth, are

acceptable Example 9.1 creates a new Array object called book and assigns strings to

each of its elements

Another popular way to declare an array is with the literal notation This is a quick

and easy way to declare and populate an array in one step:

var friends = [ "John", "Jane", "Niveeta", "Su" ];

Using the new Constructor. To create an Array object, call the Array() constructor

with the new keyword and optionally pass information to the constructor if you know

the size and/or what elements you want to assign to the array When a size is supplied

but not values, the empty elements will be assigned undefined JavaScript provides a

number of methods to manipulate the array (these are listed in the “Array Methods” on

page 227)

E X A M P L E 9 1

<html>

<head><title>The Array Object</title>

<h2>An Array of Books</h2>

<script type="text/javascript">

1 var book = new Array(6); // Create an Array object

book[1] = "Huckleberry Finn";

book[2] = "The Return of the Native";

book[3] = "A Christmas Carol";

book[4] = "The Yearling";

book[5] = "Exodus";

</script>

</head>

<body bgcolor="lavender">

<big>

<script type="text/javascript">

4 document.write("book[" + i + "] "+ book[i] + "<br />");

}

</script>

</big>

</body>

</html>

Trang 4

Creating an Array Literal. The array literal is a quick way to create and populate an

array To use the literal notation (array), the array is given a name and assigned a list of

elements The elements are separated by commas and enclosed between a set of square

brackets

var myarray=["Joe", "Bob", "Ken"]

Once declared, a literal array behaves like a normal array using index values starting

at 0, and so on Current best-practice tells us that the literal way of creating an array is

preferred to using the new keyword

Can you see the difference between the following array declarations?

var array1 = new Array(10);

var array2 = [ 10 ];

The first array is specified to be a 10-element array The second array is initialized

with the value of the first element being the number 10

E X P L A N A T I O N

1 The variable book is assigned a reference to a new Array object containing six

el-ements You can leave out the size 6 and JavaScript will dynamically build the

ar-ray as you add elements to it

2 The first element of the book array is assigned the string “War and Peace” Array

indexes start at zero

3 The special for loop is used to access each of the elements in the book array where

i is a variable used to represent the index value.

4 Each of the elements of the book array are displayed in the browser (see Figure 9.3).

Figure 9.3 The book array elements and their values.

Trang 5

Populating an Array with a for Loop. Populating an array is the process of

assign-ing values to it In Example 9.3, the for loop is used to fill an array The initial value of

the index starts at zero; the looping will continue as long as the value of the index is less

than the final size of the array

E X A M P L E 9 2

<html>

<head><title>The Literal Way</title>

<h2>An Array of Pets</h2>

<script type="text/javascript">

1 var pet = [ "Fido", "Slinky", "Tweetie","Wanda" ];

</script>

</head>

<body bgcolor="lavender">

<font size="+2">

<script type="text/javascript">

3 document.write("pet[" + i + "] "+ pet[i] + "<br />");

}

</script>

</font>

</body>

</html>

E X P L A N A T I O N

1 The variable pet is assigned a list enclosed in square brackets This is called an

ar-ray literal

2 The special for loop is used to access each of the elements in the pet array where

this example represents the index value, whether a number or a string

3 Each of the elements of the pet array is displayed in the browser (see Figure 9.4).

Figure 9.4 An array literal and its output.

Trang 6

Creating and Populating an Array in One Step. When creating an array, you

can populate (assign elements to) it at the same time by passing the value of the

ele-ments as arguele-ments to the Array() constructor Later on, you can add or delete eleele-ments

as you wish See Example 9.4

E X A M P L E 9 3

<html>

<head><title>The Array Object</title></head>

<body>

<h2>An Array of Numbers</h2>

<script type="text/javascript">

2 for(var i=0; i < years.length; i++ ){

4 document.write("years[" + i + "] = "+ years[i]

+ "<br />");

}

</script>

</body>

</html>

E X P L A N A T I O N

1 The Array() constructor is called to create a 10-element array called years.

2 The for loop starts with an initial value of i set to 0, which will be the value of the

first index in the array As long as the value of i is less than the length of the array,

the body of the loop will be executed Each time through the loop, i is

increment-ed by 1

3 The array is populated here Each time through the loop, years[i] is assigned the

value of i + 2000.

4 The value of the new array element is displayed for each iteration of the loop (see

Figure 9.5)

Figure 9.5 A for loop is used to populate an array: Output from Example 9.3.

Trang 7

9.2.2 Array Object Properties

The Array object only has three properties, constructor, length, and prototype (see Table

9.1) In Chapter 8, we talked about the constructor property and the prototype property

The value of the constructor property is the name of the constructor function that created

the object The prototype property allows you to customize objects All objects have this

property, which allows you to add new properties and methods

E X A M P L E 9 4

<html>

<head><title>The Array Object</title></head>

<body>

<h2>An Array of Colored Strings</h2>

<script type="text/javascript">

1 var colors = new Array("red", "green", "blue", "purple");

3 document.write("<font color='"+colors[i]+"'>");

4 document.write("colors[" + i + "] = "+ colors[i]

+ "<br />");

}

</script>

</body>

</html>

E X P L A N A T I O N

1 A new array called colors is created and assigned four colors.

2 The special for loop iterates through each element of the colors array, using i as

the index into the array

3 The color of the font is assigned the value of the array element

4 The value of each element of the colors array is displayed The color of the font

matches the value (see Figure 9.6) Make sure the background color is not the

same color as the font or you won’t be able to see the font

Figure 9.6 Each string is a different font color: Output from Example 9.4.

Trang 8

The property most used with arrays is the length property, which determines the

number of elements in the array, that is, the size of the array You can also use this

prop-erty to set the size of an array; for example, if you set the length to 0, all elements of the

array will be removed

Table 9.1 Array Properties

Property What It Does

constructor References the object’s constructor.

length Returns the number of elements in the array

prototype Extends the definition of the array by adding properties and

methods.

E X A M P L E 9 5

<html>

<head><title>Array Properties</title>

<h2>Array Properties</h2>

<script type="text/javascript">

1 var book = new Array(); // Create an Array object

book[0] = "War and Peace"; // Assign values to elements book[1] = "Huckleberry Finn";

book[2] = "The Return of the Native";

book[3] = "A Christmas Carol";

book[4] = "The Yearling";

book[5] = "Exodus";

</script>

</head>

<body bgcolor="lightblue">

<big>

<script type="text/javascript">

" elements<br />");

document.write("The book's constructor is: "+

document.write("The book has been trashed! The first book is"+

6 document.write("<br />The size is now "+ book.length);

</script>

</big>

</body>

</html>

Trang 9

9.2.3 Associative Arrays

JavaScript allows use of a string value as an index of an array An array that uses a string

as an index value instead of a number is called an associative array There is an

associa-tion between the index and the value stored at that locaassocia-tion The index is often called a

key and the value assigned to it, the value Key/value pairs are a common way of storing

and accessing data In the following array called states, there is an association between

the value of the index, the abbreviation for a state (e.g., “CA”), and the value stored

there—the name of the state (e.g., “California”) The special for loop can also be used to

iterate through the elements of an associative array We will see many examples

through-out the rest of the text where associative arrays are used.1

E X P L A N A T I O N

1 An Array object is declared.

2 The length property is used to get the length of the array The length is 6.

3 The book is an Array object created by the Array() constructor The constructor

property shows that this is native (primitive) code and the name of the

construc-tor function is Array().

4 The book array object is set to a length of 0, meaning all elements with an index

of 0 or more will be removed from the array, leaving an empty array If you set the

length to 2, all values with index value of 2 or more will be removed

5 The value is undefined It was removed by setting the length of the array to 0.

6 All the elements of the array have been removed; its length is now 0 Figure 9.7

shows the output

Figure 9.7 Array properties.

1 This type of array has nothing to do with the built-in Array object Saying object[“property”] is just

another way of saying object.property It’s another way of representing an object’s property This means

that the Array object’s length property is not used with associative arrays, nor do the Array methods apply,

which are covered later in this chapter

Trang 10

Bracket vs Dot Notation. This is an important note: any object, not just the Array

object, can use the square bracket notation to reference it’s properties The following two

expressions are interchangeable:

cat.color = "black";

cat["color"] = "black";

E X A M P L E 9 6

<html>

<head><title>Associative Arrays</title></head>

<body>

<h2>An Array Indexed by Strings</h2>

1 <script type="text/javascript">

3 states["CA"] = "California";

states["ME"] = "Maine";

states["MT"] = "Montana";

document.write("The index is:<em> "+ i );

document.write(".</em> The value is: <em>" + states[i]

+ ".</em><br />");

}

</script>

</body>

</html>

E X P L A N A T I O N

1 The JavaScript program starts here

2 The Array() constructor is called and returns a new Array object called states.

3 The index into the array element is a string of text, “CA” The value assigned is

“California” Now there is an association between the index and the value.

4 The special for loop is used to iterate through the Array object The variable, i,

represents the index value of the array, and states[i] represents the value found

there It reads: For each index value in the array called states, get the value

asso-ciated with it (see Figure 9.8)

Figure 9.8 An associative array.

Ngày đăng: 04/07/2014, 02:20