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:

<!-- Array_Object_Methods.html
   Copyright (c) 2013 by Dr. Herong Yang,
<head><title>Array Object Methods</title></head>
<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 ths array.
   animals.unshift("Bird", "Eagle");

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

   // Sort the array in ascending order

   // Reverse it in descending order

   // 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"); 

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


 PDF Printing Version