Java Reference
In-Depth Information
So how do you create an array? This is slightly different from declaring a normal variable. To create
a new array, you need to declare a variable name and tell JavaScript that you want it to be a new
array using the new keyword and the Array() function. For example, you could define the array
myArray like this:
var myArray = new Array();
Note that, as with everything in JavaScript, the code is case‐sensitive, so if you type array() rather
than Array() , the code won't work. Using the new operator is explained in Chapter 5.
Today's JavaScript developers create arrays like this:
var myArray = [];
This uses an array literal to create the array. It is functionally the same as using new Array() , but it
requires less typing. There is no right or wrong way to create an array, but for the remainder of this
book, we use the array literal to create arrays.
As with normal variables, you can also declare your variable first, and then tell JavaScript you want
it to be an array. For example:
var myArray;
myArray = [];
You have seen how to declare a new array, but how do you store your pieces of data inside it? You
can do this when you define your array by including your data inside the square brackets, with each
piece of data separated by a comma. For example:
var myArray = ["Paul",345,"John",112,"Bob",99];
Here the first item of data, "Paul" , will be put in the array with an index of 0 . The next piece of
data, 345 , will be put in the array with an index of 1 , and so on. This means that the element with
the name myArray[0] contains the value "Paul" , the element with the name myArray[1] contains the
value 345 , and so on.
You don't have to provide an array's data when you first create the array. For example, you could
also write the preceding line like this:
var myArray = [];
myArray[0] = "Paul";
myArray[1] = 345;
myArray[2] = "John";
myArray[3] = 112;
myArray[4] = "Bob";
myArray[5] = 99;
You use each element name as you would a variable, assigning them with values. You learn this
method of declaring the values of array elements in the following “Try It Out” section.
Obviously, in this example the first way of defining the data items is much easier. However, there
will be situations in which you want to change the data stored in a particular element in an array
Search WWH ::




Custom Search