本文介绍了迭代对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! var obj = {name:Simon,年龄:20,衣服:{style:simple,hipster: false}} for(var propt in obj){alert(propt +':'+ obj [propt]); } 变量如何 propt 表示对象的属性?它不是内置方法或属性。那为什么它会出现对象中的每个属性?解决方案迭代属性需要额外的 hasOwnProperty check: for(对象中的var属性){ if(object。 hasOwnProperty(property)){ // do stuff } } 这是必要的,因为对象的原型包含对象的附加属性,这些属性在技术上是对象的一部分。这些附加属性继承自基础对象类,但仍然是 object 的属性。 hasOwnProperty 只是检查这是否是特定于此类的属性,而不是从基类继承的属性。 var obj = {name: "Simon",age: "20",clothing: {style: "simple",hipster: false}}for(var propt in obj){alert(propt + ': ' + obj[propt]);}How does the variable propt represent the properties of the object? It's not a built-in method, or property. Then why does it come up with every property in the object? 解决方案 Iterating over properties requires this additional hasOwnProperty check: for (var property in object) { if (object.hasOwnProperty(property)) { // do stuff }}It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of object.hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class. 这篇关于迭代对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-25 11:36