
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
252
|
Chapter 11: Arrays
Summing the values of an array’s elements manually isn’t exactly the paragon of
optimized code. Later, we’ll see a much more convenient way to access an array’s
elements sequentially.
Setting an Element’s Value
To set an element’s value, we use arrayName[elementNumber] as the left-hand oper-
and of an assignment expression:
// Make an array
var cities = ["Toronto", "Montreal", "Vancouver", "Waterloo"];
// cities is now: ["Toronto", "Montreal", "Vancouver", "Waterloo"]
// Set the value of the array's first element
// cities becomes ["London", "Montreal", "Vancouver", "Waterloo"]
cities[0] = "London";
// Set the value of the array's fourth element
// cities becomes ["London", "Montreal", "Vancouver", "Hamburg"]
cities[3] = "Hamburg";
// Set the value of the array's third element
// cities becomes ["London", "Montreal", 293.3, "Hamburg"]
cities[2] = 293.3; // Notice that the datatype change is not a problem
Note that we can use any nonnegative numeric expression as the index when setting
an array element:
var i = 1;
// Set the value of element i
// cities becomes ["London", "Prague", 293.3, "Hamburg"]
cities[i] = "Prague";
Determining the Size of an Array
All arrays come with a built-in property named length, which indicates the current
number of elements (including undefined ...