"JS" for In loop object, function of hasOwnProperty ()

Source: Internet
Author: User
Tags hasownproperty

Tag:ges   div   img    name    console     prototype    ons   .com   push   

 var  obj = {name:  "  echolun   "  "  24   " , sex:  "  Span style= "COLOR: #800000" >male   " },  objname  =[], //  used to load object property name  objval=[]; //  for  (var  i in      obj) {objname.push (i); Objval.push (Obj[i]);} Console.log (objname,objval);  

It is important to note that the for In loop object accesses all object properties on the prototype chain, see below.

varobj ={name:"Echolun", Age:" -", Sex:"male"},objname=[],//used to load object property namesObjval=[];//used to load object property valuesObject.prototype.game="lastGAME"; for(varIinchobj)    {Objname.push (i); Objval.push (Obj[i]);} Console.log (Objname,objval);}

This is also the loop object, obj, but it is important to note that the game of the additional objects we added on the prototype chain is also being recycled.

So we just want to loop the corresponding object what to do, here the hasOwnProperty () method is introduced, andthe hasOwnProperty () function is used to indicate an object itself ( excluding the prototype chain ) Whether the property has the specified name. Returns true if any, otherwise false is returned.

To put it simply, it can help you point to your current loop and filter out other objects on the prototype chain, because it's very hard to make sure that someone else modifies the prototype chain, which is more secure, and then modifies the code.

varobj ={name:"Echolun", Age:" -", Sex:"male"},objname=[],//used to load object property namesObjval=[];//used to load object property valuesObject.prototype.game="lastGAME"; for(varIinchobj) {    if(Obj.hasownproperty (i)) {Objname.push (i);    Objval.push (Obj[i]); }}console.log (Objname,objval);}

See, this will filter out the game.

"JS" for In loop object, function of hasOwnProperty ()

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.