Example of "too" sharp for/in loop usage in JavaScript

Source: Internet
Author: User

Java enhanced for loop is very useful
Copy codeThe Code is as follows:
For (String str: list ){
System. out. println (str); // Where str is directly an element in the Set
}

However, the for/in loop provided for us in JavaScript is no longer that simple.
Copy codeThe 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 Benz Bentley

It looks like I got my car list

But now I have higher requirements for my garage. I hope it can be locked and self-cleaned.

Therefore
Copy codeThe 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 Benz Bentley true function () {alert ("clean ")}

Well, it says everything you know.

To avoid this embarrassment, we have to use the original for loop.
Copy codeThe 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, this is much 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.