Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

javascript - 遍历对象属性(Iterate through object properties)

 var obj = { name: "Simon", age: "20", clothing: { style: "simple", hipster: false } } for(var propt in obj){ console.log(propt + ': ' + obj[propt]); } 

How does the variable propt represent the properties of the object?

(变量propt如何表示对象的属性?)

It's not a built-in method or property.

(它不是内置方法或属性。)

Why does it come up with every property in the object?

(为什么它包含对象中的每个属性?)

  ask by Rafay translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iterating over properties requires this additional hasOwnProperty check:

(遍历属性需要此附加的hasOwnProperty检查:)

for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
        // 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 obj .

(这些附加属性是从基础对象类继承的,但仍然是obj属性。)

hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.

(hasOwnProperty仅检查该属性是否是该类的特定属性,而不是从基类继承的属性。)


It's also possible to call hasOwnProperty through the object itself:

(也可以通过对象本身调用hasOwnProperty :)

if (obj.hasOwnProperty(prop)) {
    // do stuff
}

But this will fail if the object has an unrelated field with the same name:

(但这将失败,如果对象具有一个不相关的同名字段:)

var obj = { foo: 42, hasOwnProperty: 'lol' };
obj.hasOwnProperty('foo');  // TypeError: hasOwnProperty is not a function

That's why it's safer to call it through Object.prototype instead:

(这就是为什么通过Object.prototype调用它更安全的原因:)

var obj = { foo: 42, hasOwnProperty: 'lol' };
Object.prototype.hasOwnProperty.call(obj, 'foo');  // true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...