The enhanced for loop in Java is very easy to use
for ( String str : list) {
System.out.println(str);//where str is directly the element in the collection
}
But the for/ provided for us in JavaScript The in loop is no longer that simple
var car
var garage= new Array()
garage[0] = "BMW"
garage[1] = "Mercedes-Benz"
garage[2] = "Bentley"
for (car in garage)
{
document.write(garage[car] " ")
}
//Output result: BMW Mercedes Bentley
Looks like I got my car list
But now I have higher requirements for my garage. I want it to be lockable and able to clean itself
So
var car
var garage= new Array()
garage[0] = "BMW"
garage[1] = "Mercedes-Benz"
garage[2] = "Bentley"
garage.locked = true
garage.clean = function(){
alert("Clean")
}
for (car in garage)
{
document.write(garage[car] " ")
}
//Output result: BMW Mercedes-Benz Bentley true function (){ alert ("Clean") }
Well, it tells everything it knows
In order to avoid this embarrassment, we have to use the original for loop
var car
var garage= new Array()
garage[ 0] = "BMW"
garage[1] = "Mercedes-Benz"
garage[2] = "Bentley"
garage.locked = true
garage.clean = function(){
alert("Clean")
}
for (car = 0;car < garage.length;car )
{
document.write(garage[car] " ")
}
//Output result: BMW Benz Bentley
Well, it’s much better now.