HTML and CSS Reference
In-Depth Information
Arrays
Arrays are lists of things. They can be lists of values, lists of objects, or even lists of
lists. There are a couple of ways to declare arrays. The first is to create your own Array
object, like this:
var list = new Array(10);
That declares an array with 10 slots. Arrays are numbered (or indexed) starting at 0, so
an array with ten elements has indexes from 0 to 9. You can refer to a specific item in an
array by placing the index inside square brackets after the array name. So, to assign the
first element in the array, you use the following syntax:
list[0] = “Element 1”;
There are a couple of shortcuts for declaring arrays, too. You can populate an array when
you construct the Array object like this:
var list = new Array(“red”, “green”, “blue”);
Or you can use what's called an array literal and skip the Array object entirely, like this:
var list = [“red”, “green”, “blue”];
To find out how many elements are in an array, you can use a property of the array called
length . Here's an example:
listLength = list.length
Objects
You've already been introduced to a few objects, most recently, the Array object.
JavaScript features a number of built-in objects, and the browser supplies even more
(which I discuss in the next section). The first thing you need to know about objects is
that they have properties. You just saw one property, the length property of the Array
object.
Object properties are accessed through what's known as dot notation. You can also
access properties as though they are array indexes. For example, if you have an object
named car with a property named color , you can access that property in two ways:
car.color = “blue”;
car[“color”] = “red”;
14
You can also add your own properties to an object. To add a new property to the car
object, I just have to declare it:
car.numberOfDoors = 4;
 
Search WWH ::




Custom Search