JavaScript "too" sharp for/in cycle using the sample _javascript tips

Source: Internet
Author: User
The enhanced for loop in Java is easy to use
Copy Code code as follows:

for (String str:list) {
System.out.println (str);//Where STR is directly the element of the collection.
}

But the for/in loops that are provided for us in JavaScript are not that simple.
Copy Code code as follows:

var car
var garage= new Array ()
Garage[0] = "BMW"
GARAGE[1] = "Mercedes"
GARAGE[2] = "Bentley"
For (car in garage)
{
document.write (Garage[car] + "")
}
Output result: BMW Mercedes-Benz Bentley

Looks like I got a list of my cars.

But now I have higher requirements for my garage, and I want it to be locked and clean.

So
Copy Code code as follows:

var car
var garage= new Array ()
Garage[0] = "BMW"
GARAGE[1] = "Mercedes"
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 you everything you know.

To avoid this embarrassment, we had to use the original for loop.
Copy Code code as follows:

var car
var garage= new Array ()
Garage[0] = "BMW"
GARAGE[1] = "Mercedes"
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 Mercedes-Benz Bentley

Well, that's a lot better.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.