Creating Arrays
We can create a new array with a data literal (i.e., simply typing
out all the elements) or with the special built-in array constructor
function, Array( ).
The Array Constructor
To
create an array with the
Array( )
constructor, we use the
new operator followed by the Array
keyword followed by parentheses, which yields an empty
array (one with no elements). We normally assign a newly created
array to a variable or other data container for future reference. For
example:
var myList = new Array( ); // Store an empty array in variable myListWe often want to assign initial values to an array’s elements.
We can do so by passing parameters to the Array(
) constructor when invoking it. Depending on the
parameters we supply, the constructor invocation has different
effects.
When we supply more than one argument to the Array(
) constructor or when we supply a single nonnumeric
argument to the Array( ) constructor, each
argument becomes one of the element values in our new array. For
example:
var frameLabels = new Array("intro", "section1", "section2", "home");The array stored in frameLabels would have the
following elements:
0: "intro" 1: "section1" 2: "section2" 3: "home"
When we supply exactly one numeric argument to the Array(
) constructor, it creates an array with the specified
number of empty placeholder elements:
var myList = new Array(14); // Creates an array with 14 empty elements
Arguments passed to the Array( ) constructor can be any legal expression, including compound ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access