For-in loop (for-in loops)

Source: Internet
Author: User
Tags hasownproperty

There is a very importanthasOwnProperty()When traversing object attributes, you can filter out the attributes from the prototype chain.

 

// Object
VaR man = {
Hands: 2,
Legs: 2,
Heads: 1
};

// Somewhere in the code
// A method is added to all objects.
If (typeof object. Prototype. Clone = "undefined "){
Object. Prototype. Clone = function (){};
}


// 1.
// For-in Loop
For (var I in Man ){
If (man. hasownproperty (I) {// Filter
Console. Log (I, ":", man [I]);
}
}
/* Console display results
Hands: 2
Legs: 2
Heads: 1
*/
// 2.
// Negative example:
// For-in loop without checking hasownproperty ()
For (var I in Man ){
Console. Log (I, ":", man [I]);
}
/*
Console display result
Hands: 2
Legs: 2
Heads: 1
Clone: function ()
*/

Another usehasOwnProperty()The format is to cancel the method on object. prototype. For example:

 
For (var I in Man ){
If (object. Prototype. hasownproperty. Call (man, I) {// Filter
Console. Log (I, ":", man [I]);
}
}

The advantage is that when the man object re-Defines hasownproperty, it can avoid name conflicts. It also avoids all methods for searching the object with long properties. You can use the local variable "cache" it.

VaR I, hasown = object. Prototype. hasownproperty;
For (I in Man ){
If (hasown. Call (man, I) {// Filter
Console. Log (I, ":", man [I]);
}
}
 

Strictly speaking, do not usehasOwnProperty()It is not an error. Based on the task and your confidence in the code, you can skip it to improve the speed of the loop. But when you are not sure about the content of the current object (and its prototype chain), addhasOwnProperty()More secure.

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.