Tải bản đầy đủ (.pdf) (8 trang)

Học JavaScript qua ví dụ part 26 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (887.15 KB, 8 trang )

ptg
9.3 Array Methods 227
9.3 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 deter-
mine 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).
Figure 9.12 An associative array—one key associated with more than one value.
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
ptg
228 Chapter 9 • JavaScript Core Objects
The concat() Method. The concat() method concatenates the elements passed as
arguments onto an existing array (JavaScript 1.2), returning a new concatenated list.
The method does not change the existing array in place. You must assign results to either
an existing array or a new one.


FORMAT
newArray=oldArray.concat(new elements);
EXAMPLE
names = names.concat("green, "blue");
EXAMPLE 9.10
<html>
<head>
<title>Array concat() methods</title>
</head>
<body>
<script type="text/javascript">
1 var names1=new Array("Dan", "Liz", "Jody" );
2 var names2=new Array("Tom", "Suzanne");
document.write("<b>First array: "+ names1 + "<br />");
document.write("<b>Second array: "+ names2 + "<br />");
document.write("<b>After the concatenation <br />");
3 names1 = names1.concat( names2);
document.write(names1);
</script>
</body>
</html>
EXPLANATION
1 The first Array object, called names1, is created.
2 The second Array object, called names2, is created.
3 After concatenating the names2 array to names1, the result is returned written to
names1 (see Figure 9.13). Without assigning the return value to names1, names1
will not be changed. You can return the results to a completely different array. The
concat() method allows the elements of one array to be added to another.
Figure 9.13 The Array concat() method before and after.
From the Library of WoweBook.Com

ptg
9.3 Array Methods 229
The pop() Method. The pop() method deletes the last element of an array and
returns the value popped off.
The push() Method. The push() method adds new elements onto the end of an array,
thereby increasing the length of the array. JavaScript allocates new memory as needed.
FORMAT
var return_value=Arrayname.pop();
EXAMPLE
var popped = myArray.pop();
EXAMPLE 9.11
<html>
<head><title>Array pop() method</title></head>
<body>
<script type="text/javascript">
1 var names=new Array("Tom", "Dan", "Liz", "Jody");
2 document.write("<b>Original array: "+ names +"<br />");
3 var newstring=names.pop(); // Pop off last element of array
4 document.write("Element popped: "+ newstring);
5 document.write("<br />New array: "+ names + "</b>");
</script>
</body>
</html>
EXPLANATION
1 The Array() constructor creates a new array called names and initializes the array
with four values: “Tom”, “Dan”, “Liz”, and “Jody”.
2 The contents of the array called names is displayed.
3 The last element of the array is removed. The value removed is returned and as-
signed to the variable called newstring.
4 The popped value is displayed.

5 The shortened array is displayed (see Figure 9.14).
Figure 9.14 The Array pop() method.
From the Library of WoweBook.Com
ptg
230 Chapter 9 • JavaScript Core Objects
The shift() and unshift() Methods. The shift() method removes the first element of
an array and returns the value shifted off; the unshift() method adds elements to the
beginning of the array. These methods are just like pop() and push() except that they
manipulate the beginning of the array instead of the end of it.
FORMAT
Arrayname.push(new elements); // Appended to the array
EXAMPLE
myArray.push("red", "green", "yellow");
EXAMPLE 9.12
<html>
<head><title>Array push() method</title></head>
<body>
<script type="text/javascript">
1 var names=new Array("Tom", "Dan", "Liz", "Jody");
2 document.write("<b>Original array: "+ names + "<br />");
3 names.push("Daniel","Christian");
4 document.write("New array: "+ names + "</b>");
</script>
</body>
</html>
EXPLANATION
1 An Array object called names is declared and initialized.
2 The contents of the array (i.e., all of its elements) are displayed.
3 The push() method appends two new elements, “Daniel” and “Christian”, to the
end of the names array.

4 The array has grown. It is displayed in the browser window with its new elements
(see Figure 9.15).
Figure 9.15 The Array push() method before and after.
From the Library of WoweBook.Com
ptg
9.3 Array Methods 231
The slice() Method. The slice() method copies elements of one array into a new
array. The slice() method takes two arguments: The first is the starting element in a range
of elements that will be copied, and the second is the last element in the range, but this
element is not included in what is copied. Remember that the index starts at zero, so that
a beginning position of 2 is really element 3. The original array is unaffected unless you
assign the result of the slice back to the original array.
FORMAT
var return_value=Arrayname.shift();
Arrayname.shift( new elements); // Prepended to the array
EXAMPLE
var shifted_off = myArray.shift();
myArray.shift("blue","yellow");
EXAMPLE 9.13
<html>
<head><title>Array shift() and unshift() methods</title></head>
<body>
<script type="text/javascript">
1 var names=new Array("Dan", "Liz", "Jody" );
document.write("<b>Original array: "+ names + "<br />");
2 names.shift();
document.write("New array after the shift: " + names);
3 names.unshift("Nicky","Lucy");
// Add new elements to the beginning of the array
document.write("<br />New array after the unshift: " + names);

</script>
</body>
</html>
EXPLANATION
1 A new Array object called names is created.
2 The first element of the array is shifted off, shortening the array by 1.
3 The unshift() method will prepend to the beginning of the array the names
“Nicky” and “Lucy”, thereby making it longer by two elements (see Figure 9.16).
Figure 9.16 The Array shift() and unshift() methods.
From the Library of WoweBook.Com
ptg
232 Chapter 9 • JavaScript Core Objects
The splice() Method. The splice() method removes a specified number of ele-
ments from some starting position in an array and allows you to replace those items
FORMAT
var newArray = Arrayname.slice(first element, last element);
EXAMPLE
var ArraySlice = myArray.slice(2,6); // ArraySlice contains elements
// 2 through 5 of myArray.
EXAMPLE 9.14
<html>
<head><title>Array slice() method</title></head>
<body>
<script type="text/javascript">
1 var names=new Array("Dan", "Liz", "Jody", "Christian",
"William");
document.write("<b>Original array: "+ names + "<br />");
2 var sliceArray=names.slice(2, 4);
document.write("New array after the slice: ");
3 document.write(sliceArray);

</script>
</body>
</html>
EXPLANATION
1 This is the original array of names.
2 The slice() method will start at position 2, copy Jody into the new array, then
Christian, and stop just before position 4, William. The original array is not affect-
ed by the slice.
3 The new array created by the slice() method is displayed (see Figure 9.17).
Figure 9.17 Using Array slice() to copy elements of an array.
From the Library of WoweBook.Com
ptg
9.3 Array Methods 233
with new ones. (Don’t confuse this method with the slice() method. The slice()
method copies elements, the splice() method removes and/or replaces elements.
Ropes, tapes, and films are spliced; bread, meat, and golf balls are sliced.)
FORMAT
Arrayname.splice(index position, number of elements to remove);
Arrayname.splice(index position, number of elements to remove,
replacement elements);
EXAMPLE
myArray.splice(3, 2);
myArray.splice(3, 2, "apples","oranges");
EXAMPLE 9.15
<html>
<head><title>Array splice() method</title></head>
<body>
<script type="text/javascript">
// splice(starting_pos, number_to_delete, new_values)
1 var names=new Array("Tom","Dan", "Liz", "Jody");

document.write("<b>Original array: "+ names + "<br />");
2 names.splice(1, 2, "Peter","Paul","Mary");
3 document.write("New array: "+ names + "</b>");
</script>
</body>
</html>
EXPLANATION
1 An Array object called names is declared and initialized.
2 The splice() method allows you to delete elements from an array and optionally re-
place the deleted elements with new values. The first arguments to the splice meth-
od are 1, 2. This means: start at element 1, and remove a length of 2 elements. In
this example, element 1 starts with “Dan” (element 0 is “Tom”). “Liz” is the second
element. Both “Dan” and “Liz” are removed. The next three arguments, “Peter”,
“Paul”, and “Mary”, are then inserted into the array, replacing “Dan” and “Liz”.
3 The new names array is displayed in the browser window (see Figure 9.18).
Figure 9.18 The splice() method to delete and insert elements of an array.
From the Library of WoweBook.Com
ptg
234 Chapter 9 • JavaScript Core Objects
9.4 The Date Object
JavaScript provides the Date object for manipulating date and time.
2
Like the String and
Array objects, you can create as many instances as you like.
As we’ll see, the Date object provides a number of methods for getting or setting spe-
cific information about the date and time. The date is based on the UNIX date starting
at January 1, 1970 (in Greenwich Mean Time
3
[GMT]), and doesn’t support dates before
that time. Figure 9.19 gives you an idea of the difference between GMT and local time.

Time is measured in milliseconds (one millisecond is one thousandth of a second).
Because client-side JavaScript programs run on a browser, the Date object returns times
and dates that are local to the browser, not the server. Of course, if the computer is not
set to the correct time, then the Date object won’t produce the expected results. Figure
9.20 shows a typical date and time control panel.
2. For more information about the time and date, see />3. Greenwich Mean Time (GMT) is now called Universal Coordinate Time (UTC). The current time in
Greenwich, England is five hours + New York’s present time, or eight hours + San Francisco’s present
time.
Figure 9.19 24-hour world time zones map with current time. Courtesy of
/> From the Library of WoweBook.Com

×