Array Object Instance Method Examples

This section provides a tutorial example on how to use array object methods like push(), pop(), unshift(), shift(), sort(), join(), etc.

To help you understand how some of the array object methods works, I wrote the following the JavaScript tutorial example, Array_Object_Methods.html:

<html>
<!-- Array_Object_Methods.html
   Copyright (c) 2002 HerongYang.com. All Rights Reserved.
-->
<head><title>Array Object Methods</title></head>
<body>
<pre>
<script type="text/javascript">

   // Starting the array with 2 animals
   var animals = new Array("Dog", "Cat");

   // Push more animals to the end of the array
   animals.push("Fox", "Fish");
   
   // Pop off the last animal, fish, from the array 
   var fish = animals.pop();

   // Push more animals to the front of this array.
   animals.unshift("Bird", "Eagle");

   // Pop off the first animal, bird, from the array
   var bird = animals.shift();

   // Sort the array in ascending order
   animals.sort();

   // Reverse it in descending order
   animals.reverse();

   // Join all elements into a string
   var all_four = animals.join(", ");

   // Remove 2 of them starting from the 2nd one
   animals.splice(1, 2);

   // Join them again
   var all_two = animals.join(", ");

   // Display the result
   document.write("Fish? " + fish + "\n"); 
   document.write("Bird? " + bird + "\n"); 
   document.write("All 4 animals? " + all_four + "\n"); 
   document.write("All 2 animals? " + all_two + "\n"); 
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:

Fish? Fish
Bird? Bird
All 4 animals? Fox, Eagle, Dog, Cat
All 2 animals? Fox, Cat

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

Creating, Accessing, and Manipulating Arrays

 What Is an Array

 Creating an Array Object

 Accessing Array Elements with Indexes

 Truncating and Iterating Array Elements

 Array Object Instance Methods

Array Object Instance Method Examples

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB