9.3 Array Properties and Methods


9.3 Array Properties and Methods

Since an array is an object in JavaScript, it has properties to describe it and methods to manipulate it. The length of an array, for example, can be determined by the length property, and the array can be shortened by using the pop() method. For a complete list of array properties and methods, see Tables 9.1 and 9.2.

9.3.1 Array Object Properties

The Array object only has three properties. The most used is the length property which determines the number of elements in the array, that is, the size of the array.

Table 9.1. Array object 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
 <html>     <head>     <title>Array Properties</title>     <h2>Array Properties</h2>         <script language="JavaScript"> 1  var book = new Array(6);  //  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">         <script language="JavaScript">             document.write("<h3>"); 2           document.write("The book array has "  +  book.length  + " elements<br>");         </script>     </body>     </html> (Output) The book array has 6 elements. 

EXPLANATION

  1. A six-element Array object is declared.

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

9.3.2 Array Methods

Whether you have an array of colors, names , or numbers , there are many ways you might want to manipulate the array elements. For example, you might want to add a new name or color to the beginning or end of the array, remove a number from the end of the array, or sort out all the elements, reverse the 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

The concat() Method

The concat() method concatenates the elements passed as arguments onto an existing array (JavaScript 1.2), returning a new concatenated list.

FORMAT

 
 newArray=oldArray.concat(new elements); 

Example:

 
 names  = names.concat("green, "blue"); 
Example 9.6
 <html>     <head><title>Array concat() methods</title>     </head>     <body>     <script language="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 to names1 . The concat() method allows the elements of one array to be added to another.

Figure 9.6. The concat() method. Output from Example 9.6.

graphics/09fig06.jpg

The pop() Method

The pop() method deletes the last element of an array and returns the value popped off.

FORMAT

 
 var return_value=Arrayname.pop(); 

Example:

 
 var popped = myArray.pop(); 
Example 9.7
 <html>     <head><title>Array pop() method</title>     </head>     <body>     <script language="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 intializes 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 assigned to the variable called newstring .

  4. The popped value is displayed.

  5. The shortened array is displayed. (See Figure 9.7.)

    Figure 9.7. Output from Example 9.7.

    graphics/09fig07.jpg

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

 
 Arrayname.push(new elements);  //  Appended to the array  

Example:

 
 myArray.push("red", "green", "yellow"); 
Example 9.8
 <html>     <head><title>Array push() method</title>     </head>     <body>     <script language="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 intialized.

  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.8.)

    Figure 9.8. Output from Example 9.8.

    graphics/09fig08.jpg

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

 
 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.9
 <html>     <head><title>Array shift() and unshift() methods</title>     </head>     <body>     <script language="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.9.)

    Figure 9.9. The shift() and unshift() methods. Output from Example 9.9.

    graphics/09fig09.jpg

The slice() Method

The slice() method copies elements of one array into a new array. The slice() method takes two arguments: the first number is the starting element in a range of elements that will be copied, and the second argument 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 orginal array is unaffected unless you assign the result of the slice back to the original array.

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.10
 <html>     <head><title>Array slice() method</title>     </head>     <body>     <script language="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 affected by the slice.

  3. The new array created by the slice() method is displayed. (See Figure 9.10.)

    Figure 9.10. Using slice() to create a new array.

    graphics/09fig10.jpg

The splice() Method

The splice() method [not to be confused with slice() ] removes a specified number of elements from some starting position in an array and allows you to replace those items with new ones. (Don't confuse this method with the slice() method. 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.11
 <html>     <head><title>Array splice() method</title>     </head>     <body>         <script language="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 intialized.

  2. The splice() method allows you to delete elements from an array and optionally replace the deleted elements with new values. The first arguments to the splice method 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.11.)

    Figure 9.11. The splice() method. Output from Example 9.11.

    graphics/09fig11.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net