Reading and Writing Array Elements
You access an element of an array using the [] operator. A reference to the array should
appear to the left of the brackets. An arbitrary expression that has a
non-negative integer value should be inside the brackets. You can use
this syntax to both read and write the value of an element of an
array. Thus, the following are all legal JavaScript
statements:
vara=["world"];// Start with a one-element arrayvarvalue=a[0];// Read element 0a[1]=3.14;// Write element 1i=2;a[i]=3;// Write element 2a[i+1]="hello";// Write element 3a[a[i]]=a[0];// Read elements 0 and 2, write element 3
Remember that arrays are a specialized kind of object. The
square brackets used to access array elements work just like the
square brackets used to access object properties. JavaScript converts
the numeric array index you specify to a string—the index 1 becomes the string "1"—then uses that string as a property
name. There is nothing special about the conversion of the index from
a number to a string: you can do that with regular objects,
too:
o={};// Create a plain objecto[1]="one";// Index it with an integer
What is special about arrays is that when you use property names
that are non-negative integers less than
232, the array automatically maintains the
value of the length property for
you. Above, for example, we created an array a with a single element. We then assigned
values at indexes 1, 2, and 3. The length property of the array changed ...
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