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.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn