From the Library of WoweBook.Com 216 Chapter • JavaScript Pets From the Library of WoweBook.Com 216 Chapter • JavaScript Pets
  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

Nội dung

chapter JavaScript Core Objects 9.1 What Are Core Objects? Like an apple, JavaScript has a core, and at its core are objects Everything you 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, regular expressions, numbers, and other useful entities The good news is that the core objects are consistent across different implementations and platforms and were standardized 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 complete 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 subscript 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 “red” “blue” color[0] Figure 9.1 color[1] “green” color[2] “yellow” color[3] A numeric Array object called color Index values are numbers 213 From the Library of WoweBook.Com 214 Chapter “#FF0000” hex[“red”] Figure 9.2 9.2.1 “#0000FF” • JavaScript Core Objects “#00FF00” hex[“blue”] hex[“green”] An associative Array object called hex Index values are strings 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 function, 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 constructed, called a dense array, but this is not required either The following array is called array_name and its size is not specified F O RM A T var array_name = new Array(); Example: var months = new Array(); months[0]="January"; months[1]="February"; months[2]="March" 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"); From the Library of WoweBook.Com 9.2 Array Objects 215 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 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) EXAMPLE 9.1 The Array Object An Array of Books var book = new Array(6); // Create an Array object book[0] = "War and Peace"; // Assign values to its elements book[1] = "Huckleberry Finn"; book[2] = "The Return of the Native"; book[3] = "A Christmas Carol"; book[4] = "The Yearling"; book[5] = "Exodus"; for(var i in book){ document.write("book[" + i + "] "+ book[i] + ""); } From the Library of WoweBook.Com 216 Chapter • JavaScript Core Objects EXPLANATION The variable book is assigned a reference to a new Array object containing six elements You can leave out the size and JavaScript will dynamically build the array as you add elements to it The first element of the book array is assigned the string “War and Peace” Array indexes start at zero 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 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 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 From the Library of WoweBook.Com 9.2 Array Objects EXAMPLE 217 9.2 The Literal Way An Array of Pets var pet = [ "Fido", "Slinky", "Tweetie","Wanda" ]; for(var i in pet){ document.write("pet[" + i + "] "+ pet[i] + ""); } EXPLANATION The variable pet is assigned a list enclosed in square brackets This is called an array literal 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 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 Populating an Array with a for Loop Populating an array is the process of assigning 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 From the Library of WoweBook.Com 218 Chapter EXAMPLE • JavaScript Core Objects 9.3 The Array Object An Array of Numbers var years = new Array(10); for(var i=0; i < years.length; i++ ){ years[i]=i + 2000; document.write("years[" + i + "] = "+ years[i] + ""); } EXPLANATION The Array() constructor is called to create a 10-element array called years 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 incremented by The array is populated here Each time through the loop, years[i] is assigned the value of i + 2000 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 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 elements as arguments to the Array() constructor Later on, you can add or delete elements as you wish See Example 9.4 From the Library of WoweBook.Com 9.2 Array Objects EXAMPLE 219 9.4 The Array Object An Array of Colored Strings var colors = new Array("red", "green", "blue", "purple"); for(var i in colors){ document.write(""); document.write("colors[" + i + "] = "+ colors[i] + ""); } EXPLANATION A new array called colors is created and assigned four colors The special for loop iterates through each element of the colors array, using i as the index into the array The color of the font is assigned the value of the array element 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 9.2.2 Each string is a different font color: Output from Example 9.4 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 From the Library of WoweBook.Com 220 Chapter • JavaScript Core Objects 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 property 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 EXAMPLE 9.5 Array Properties Array Properties 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"; document.write("The book array has " + book.length + " elements"); document.write("The book's constructor is: "+ book.constructor + ""); book.length=0; document.write("The book has been trashed! The first book is"+ book[0] ); document.write("The size is now "+ book.length); From the Library of WoweBook.Com 9.2 Array Objects 221 EXPLANATION An Array object is declared The length property is used to get the length of the array The length is 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 constructor function is Array() The book array object is set to a length of 0, meaning all elements with an index of 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 or more will be removed The value is undefined It was removed by setting the length of the array to All the elements of the array have been removed; its length is now Figure 9.7 shows the output Figure 9.7 9.2.3 Array properties 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 association between the index and the value stored at that location 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 throughout the rest of the text where associative arrays are used.1 This type of array has nothing to 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 the Array methods apply, which are covered later in this chapter From the Library of WoweBook.Com 222 Chapter EXAMPLE • JavaScript Core Objects 9.6 Associative Arrays An Array Indexed by Strings var states = new Array(); states["CA"] = "California"; states["ME"] = "Maine"; states["MT"] = "Montana"; for( var i in states ){ document.write("The index is: "+ i ); document.write(". The value is: " + states[i] + "."); } EXPLANATION The JavaScript program starts here The Array() constructor is called and returns a new Array object called states 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 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 associated with it (see Figure 9.8) Figure 9.8 An associative array 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"; From the Library of WoweBook.Com 9.2 Array Objects 223 The bracket notation allows you to use either a string or variable as the index value, whereas the dot notation requires the literal name of the property EXAMPLE 9.7 cat = new Object(); c = "color" cat["name"] = "Powder"; // same as cat.name = “Powder” cat[c] = "gray"; // same as cat.color = “gray”; document.write(cat.name + " is " + cat.color + ""); document.write(cat["name"] + " is " + cat[c] + ""); EXPLANATION A new cat object is instantiated The variable c is assigned the string “color” The square brackets contain an index value that also represents a property for the object We could have written this as cat.name = “Powder” The variable c is used as the index value within the square brackets Using this notation would allow you to easily change the value of the variable, thereby changing the property of the object A property of the cat object can be accessed directly with the dot notation, or represented with a string or variable within the square brackets (see Figure 9.9) Figure 9.9 9.2.4 Properties of the cat object accessed with bracket or dot notation Nested Arrays An array can consist of another set of arrays Take, for example, a row of seats in a movie theater One row of seats would represent a one-dimensional array, but the theater has more than one row To get to your seat you need to not only know what row, but the number of the seat as well To create a two-dimensional array, each row is a new array To find an element in the array we will use two index values, one for the row and one for the column; for example, array_name[0][0] represents the first element in the first row The array in Figure 9.10 consists of three rows and three columns: From the Library of WoweBook.Com 224 Chapter • JavaScript Core Objects column row Figure 9.10 An array of three arrays Using the Array constructor, the following example is an array consisting of three arrays var array_name=new Array(new Array(77,88,99), new Array(50,60,99), new Array(99,88,78) ); or the literal and easier way: var array_name= [ [77,88,99], [50,60,99], [99,88,78] ]; The first row is array_name[0], the first element in the first row is array_name[0][0], and the last element is array_name[2][2] (JavaScript will not complain if the number of elements in each of the nested arrays varies.) EXAMPLE 9.8 Two-dimensional array Grade Sheet var grades= [ [77,88,99,75], [50,60,99,89], [99,88,78,92] ]; // alert(grades.length); Output is // alert(grades); Output is 77,88,99,75,50,60,99,89, // 99,88,78,92 From the Library of WoweBook.Com 9.2 Array Objects EXAMPLE 225 9.8 ( C O N T I N U E D) for (var i=0; i < grades.length; i++) { for (var j=0; j < grades[i].length; j++) { document.write( ""+grades[i][j] + ""); } document.write(""); } EXPLANATION A two-dimensional array (array of arrays) is created using the literal notation The outer set of square brackets surrounds the set of rows nested within them Each nested row is enclosed in its own set of square brackets and each row separates with a comma (see Figure 9.11) This outer for loop will cycle through each row The length property determines the size of the row, which is The nested for loop is used to cycle through each of the elements in a row The two index values represent the rows, i, and its element, j, respectively The tag closes the table row Figure 9.11 Two-dimensional array A Key in an Associative Array with More Than One Value It is possible that the key of an associative array is associated with more than one value To accomplish this, rather than a single value, a new array object is assigned as a set of values, as shown in Example 9.9 From the Library of WoweBook.Com 226 Chapter EXAMPLE • JavaScript Core Objects 9.9 Associative Array

var student=new Array(); student["Name"]="John Doe"; //one key, one value student["Courses"]=new Array("Math","English", "PE"); student["Phones"]=new Array("415-333-1234","530-345-5432"); document.write("The student's name is " + student["Name"] + "."); document.write("His courses are " + student["Courses"] + "."); document.write("His favorite course is "+ student["Courses"][2] + "."); document.write("His cell phone number is " + student["Phones"][0] + ".");

EXPLANATION A new array object called student is instantiated An index or key in the student array is a string of text, “Name” assigned a single value, “John Doe” Now there is an association between the index and the value The index key is “Courses” The student takes more than one course A new Array is created with the values of the courses assigned to the key, an array with a nested array The index key is “Phones” The student has two phones A new Array is created with two phone numbers assigned to the key, an array with a nested array To get the name of the student, the “Name” is used as an index, also called the key To get a list of all the courses, the key/index in the array is “Courses” To get one of the courses out of the list, two index values are needed, one to key into the courses and one to select a specific course Because array index values start at 0, student [“Courses”][2] gets the third course, “PE” Again two index values are need to get one of the phone numbers student["Phones"][0] gets the value of the first phone The output is shown in Figure 9.12 From the Library of WoweBook.Com 9.3 Array Methods Figure 9.12 9.3 227 An associative array—one key associated with more than one value Array Methods Because an array is an object in JavaScript, it has properties to describe it and methods to manipulate it The length property of an array was used in previous examples to determine the size of an array Now we will look at methods that allow you to manipulate arrays such as adding a new element at the beginning or end of an array, removing an element from the end of an array, reversing an array, and so on JavaScript provides a whole set of methods for doing all of these things and more (see Table 9.2) Table 9.2 Array Methods Method What It Does concat() Concatenates elements from one array to another array join() Joins the elements of an array by a separator to form a string pop() Removes and returns the last element of an array push() Adds elements to the end of an array reverse() Reverses the order of the elements in an array shift() Removes and returns the first element of an array slice() Creates a new array from elements of an existing array sort() Sorts an array alphabetically or numerically splice() Removes and/or replaces elements of an array toLocaleString() Returns a string representation of the array in local format toString() Returns a string representation of the array unshift() Adds elements to the beginning of an array From the Library of WoweBook.Com ... type="text /javascript" > for(var i in book){ document.write("book[" + i + "] "+ book[i] + ""); } From the Library of WoweBook.Com 216 Chapter • JavaScript. .. Pets var pet = [ "Fido", "Slinky", "Tweetie","Wanda" ]; for(var i in... WoweBook.Com 218 Chapter EXAMPLE • JavaScript Core Objects 9.3 The Array Object An Array of Numbers var years = new

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