遍历对象属性 [英] Iterate through object properties

查看:33
本文介绍了遍历对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var obj = {
    name: "Simon",
    age: "20",
    clothing: {
        style: "simple",
        hipster: false
    }
}

for(var propt in obj){
    console.log(propt + ': ' + obj[propt]);
}

变量propt如何表示对象的属性?它不是内置方法或属性.为什么它把对象中的每一个属性都拿出来?

How does the variable propt represent the properties of the object? It's not a built-in method or property. Why does it come up with every property in the object?

推荐答案

迭代属性需要额外的 hasOwnProperty 检查:

Iterating over properties requires this additional hasOwnProperty check:

for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
        // do stuff
    }
}

这是必要的,因为对象的原型包含对象的附加属性,这些属性在技术上是对象的一部分.这些附加属性是从基对象类继承的,但仍然是 obj 的属性.

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.

hasOwnProperty 只是检查这是否是该类特有的属性,而不是从基类继承的属性.

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:

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

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

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

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

这篇关于遍历对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆