Creating an Array Object
<< Creating, Accessing, and Manipulating Arrays
<< JavaScript Tutorials - Herong's Tutorial Examples
This section provides a tutorial example on how to create array objects in JavaScript.
There are 3 ways to create a new array object:
1. Using the array literal - A new array object can be created by using the array literal syntax of [exp1, exp2, ...]. For example:
var colors = ["Red", "Green", "Blue"]; var account = ["Saving", 999.99, true];
2. Calling the array constructor - A new array object can be created by calling the array constructor of (new Array(exp1, exp, ...)). For example:
var colors = new Array("Red", "Green", "Blue"); var account = new Array("Saving", 999.99, true);
3. Calling the array function - A new array object can be created by calling the array function of (array(exp1, exp, ...)). For example:
var colors = Array("Red", "Green", "Blue"); var account = Array("Saving", 999.99, true);
Here is a tutorial example JavaScript that shows you how to create new array objects:
<html> <!-- Create_Arrays.html Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/ --> <head><title>Create Arrays</title></head> <body> <pre> <script type="text/javascript"> // Using array literal var my_saving = ["Saving", 999.99, true]; // Using array constructor var my_checking = new Array("Checking", 9.99, true); // Using array function var my_stock = Array("Stock", 99999.99, true); // Creating an empty array var new_account = []; document.write(my_checking[0]+": "+my_checking[1]+"\n"); document.write(my_saving[0]+": "+my_saving[1]+"\n"); document.write(my_stock[0]+": "+my_stock[1]+"\n"); document.write(new_account[0]+": "+new_account[1]+"\n"); </script> </pre> </body> </html>
The output of this sample JavaScript is:
Checking: 9.99 Saving: 999.99 Stock: 99999.99 undefined: undefined
Sections in This Chapter
What Is an Array?
Accessing Array Elements with Indexes
Truncating and Iterating Array Elements
Array Object Instance Methods
Array Object Instance Method Examples