
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Other Operators
|
139
Array-Element/Object-Property Operator
As we’ll see in Chapters 11 and 12, we use the [] operator to retrieve and set the
value of an array element or an object property. When accessing an array, it takes the
form:
array[element]
where array is the name of an array or an array literal and element is an expression
that resolves to a zero-relative, nonnegative integer representing the index of the
array element to access.
When accessing an object, the
[] operator takes the form:
object[property]
where object is an object name or object literal and property is any expression that
resolves to a string representing the name of the object property to access.
When used on the left side of an assignment operator (
=), the element or property is
assigned the new value shown on the right side of the expression:
var colors = new Array(); // Create a new array
colors[0] = "orange"; // Set its first element
colors[1] = "green"; // Set its second element
var ball = new Object(); // Create a new object
var myProp = "xVelocity"; // Store a string in a variable
ball["radius"] = 150; // Set the radius property
ball[myProp] = 10; // Set the xVelocity property through myProp
When used anywhere else, the expression returns the value of the specified element
or property:
diameter = ball["radius"] ...