Java Reference
In-Depth Information
The
length
property of an
Array
object is writable, nonenumerable, and
nonconfigurable. If you do not want someone to change it in code, you can make it
nonwritable. The nonwritable
length
property will still be automatically changed when
you add and remove elements from the array. The following code shows this rule:
var names = new Array("Fu", "Li", "Do", "Ho");
// Make the length property non-writable.
Object.defineProperty(names, "length", {writable:false});
// The length property cannot be changed directly anymore
names.length = 0; // No effects
// Add a new element
names[4] = "Nu"; // names.length changes from 4 to 5
Iterating Over Array Elements
If you are interested in iterating all properties, including elements, of an array, you
can simply use the
for..in
and
for..each..in
statements. These statements are not
supposed to iterate arrays in any specific order. As the title of this section suggests, I am
going to discuss how to iterate over only the elements of arrays, particularly when arrays
are sparse. If you add only elements to an array (not any nonelement properties), which
you will do in most cases, using the
for..in
and
for..each..in
statements work fine for
both dense and sparse.
Using the for Loop
If you know that the array is dense, you can use the simple
for
loop to iterate the array,
like so:
// Create a dense array
var names = new Array("Fu", "Li", "Do");
// Use a for loop to iterate all elements of an array
for(var i = 0, len = names.length; i < len; i++) {
print("names[" + i + "]=" + names[i]);
}
names[0]=Fu
names[1]=Li
names[2]=Do
Search WWH ::
Custom Search