Js hasownproperty usage example _ basic knowledge

Source: Internet
Author: User
We may often use forin in js to traverse attributes in objects. Of course, the attributes obtained in forin can only be enumeration attributes, it will traverse the attributes of the object (including the attributes of the prototype). You can see the following example:
There is such a piece of code:

The Code is as follows:


Var array = [];
Array. push (1 );
Array. push (2 );
Array. push (3 );
For (var I in array ){
Console. log (I + ":" + array [I]);
}


What will be output at this time? Of course it is
However, if Array. prototype. say = "hello" is added before for in ";
What will be output when I run it again?

The Code is as follows:


Say: hello


See it. At this time, it will output the properties of the prototype.
In many cases, we do not need to traverse the properties of the prototype. Another reason is that the objects we currently use cannot be guaranteed. Do other developers have them, what about adding some attributes to its prototype? So, let's filter out the attributes of our object. At this time, the hasOwnProperty method is used as follows:

The Code is as follows:


For (var I in array ){
If (array. hasOwnProperty (I )){
Console. log (I + ":" + array [I]);
}
}


What will be output now? Of course it is.
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.