Java Reference
In-Depth Information
// Print all array elements using a for loop
print("Using a for loop:");
for(var i = 0, len = names.length; i < len; i++) {
print("names[" + i + "] = " + names[i]);
}
// Print all properties of the array using a for..in loop
print("Using a for..in loop:");
for(var prop in names) {
print("names[" + prop + "] = " + names[prop]);
}
names.length = 4
Using a for loop:
names[0] = Fu
names[1] = Li
names[2] = Ho
names[3] = Su
Using a for..in loop:
names[0] = Fu
names[1] = Li
names[2] = Ho
names[3] = Su
names[nationality] = Chinese
Here are a few points to note about this example:
It created an array with three elements with at indexes 0, 1, and 2.
At this point, the length of the array is 3.
It added an element with the value of “Su” at index 3. By adding this
element, the length of the array is automatically increased to 4.
It adds a property named “nationality.” This property is simply a
property, not an element, because its name is a string that is not
convertible to an index. Adding this property does not affect the
length of the array. That is, the length stays at 4.
When it uses the for loop to print the array, the property named
"nationality" is not printed because the code loops though the
indexes, not all properties.
When it uses the
for..in loop all elements along with the
“nationality” property is printed, because the for..in loop
iterates over all properties of the object. This proves that all
elements of an array are properties, but all properties are not
elements.
Search WWH ::




Custom Search