Examples of for-in traversal in JavaScript introduction _javascript Tips

Source: Internet
Author: User
Absrtact: The loop counter of the for-in traversal is a string type, which, when traversing an object, is the object property/method name, and the array element subscript index when traversing it, unlike the normal for loop, for-in lists the inherited properties/methods, which require special attention when used.

In addition to the traditional for loop, JavaScript defines the for-in for traversal operations, and differs in usage depending on the data source.
(1) Traversing the object:
Copy Code code as follows:

var fish = {
Head:1,
Tail:1,
}
For (var prop in fish) {
Console.log (Fish[prop]);
}

When debugging observe: Prop in turn is ' head ', ' tail ', that is, when traversing object properties is a string type exists, the loop counter is the object's property name.
(2) traversing the array
Copy Code code as follows:

var arr = [' One ', ' two ', ' three '];
For (Var prop in arr) {
Console.log (prop);
}

observed during debugging: Prop is ' 0 ', ' 1 ', which is still in the string type when traversing the array, and the loop counter is the subscript for the array element. (You can try the For loop output at this point and the result is consistent with for-in)
If the code adds:
Copy Code code as follows:

if (Object.prototype.clone = = ' undefined ')
Object.prototype.clone = function () {};

The output result is: 0,1,clone
If you use the For loop output at this point, you are still 0, 1, that is, the for-in loop loops through the attributes of the type that the data source of the current operation has (also output clone when the object fish uses for-in), So it requires the use of for-in to pull a string: If only the object owned property operations, you need to remove inherited attributes, such as the hasOwnProperty () method.
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.