Home  >  Article  >  Web Front-end  >  Examples of “too” sharp for/in loop usage in JavaScript_javascript tips

Examples of “too” sharp for/in loop usage in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:19:20894browse

The enhanced for loop in Java is very easy to use

Copy the code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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