HTML and CSS Reference
In-Depth Information
Listing 7.7 Looping arrays with for and for-in
TestCase("ArrayLoopTest", {
"test looping should iterate over all items":
function () {
var array = [1, 2, 3, 4, 5, 6];
var result = [];
// Standard for-loop
for(vari=0,l=array.length; i < l; i++) {
result.push(array[i]);
}
assertEquals("123456", result.join(""));
},
"test for-in loop should iterate over all items":
function () {
var array = [1, 2, 3, 4, 5, 6];
var result = [];
for (var i in array) {
result.push(array[i]);
}
assertEquals("123456", result.join(""));
}
});
These two loops both attempt to copy all the elements of one array onto another,
and then join both arrays into a string to verify that they do indeed contain the same
elements. Running this test reveals that the second test fails with the message in
Listing 7.8.
Listing 7.8 Result of running test in Listing 7.7
expected "123456" but was "123456function () { [... snip]"
To understand what's happening, we need to understand the for-in enu-
meration. for (var property in object) will fetch the first enumerable
property of object . property is assigned the name of the property, and the
body of the loop is executed. This is repeated as long as object has more enu-
merable properties, and the body of the loop does not issue break (or return if
inside a function).
 
Search WWH ::




Custom Search