Javascript 遍历对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8312459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through object properties
提问by Rafay
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? It's not a built-in method or property. Why does it come up with every property in the object?
变量如何propt
表示对象的属性?它不是内置方法或属性。为什么它提出了对象中的每个属性?
回答by
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
回答by Danny R
As of JavaScript 1.8.5 you can use Object.keys(obj)
to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key)
).
从 JavaScript 1.8.5 开始,您可以使用Object.keys(obj)
来获取在对象本身上定义的属性数组(为 返回 true 的属性obj.hasOwnProperty(key)
)。
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
This is better (and more readable) than using a for-in loop.
这比使用 for-in 循环更好(也更易读)。
Its supported on these browsers:
这些浏览器支持它:
- Firefox (Gecko): 4 (2.0)
- Chrome: 5
- Internet Explorer: 9
- 火狐(壁虎):4 (2.0)
- 铬:5
- Internet Explorer:9
See the Mozilla Developer Network Object.keys()'s referencefor futher information.
有关更多信息,请参阅Mozilla 开发人员网络Object.keys()的参考。
回答by Frank Roth
Girls and guys we are in 2019 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:
小伙子们,我们在 2019 年,我们没有那么多时间打字……所以让我们来做一个很酷的新奇幻 ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
回答by Marc B
It's the for...in statement
(MDN, ECMAScript spec).
这是for...in statement
(MDN,ECMAScript 规范)。
You can read it as "FORevery property INthe obj
object, assign each property to the PROPTvariable in turn".
你可以把它读作“ FOR每个属性IN的obj
对象,每个属性分配给PROPT依次变量”。
回答by Marc B
In up-to-date implementations of ES, you can use Object.entries
:
在 ES 的最新实现中,您可以使用Object.entries
:
for (const [key, value] of Object.entries(obj)) { }
or
或者
Object.entries(obj).forEach(([key, value]) => ...)
If you just want to iterate over the values, then use Object.values:
如果您只想迭代这些值,请使用 Object.values:
for (const value of Object.values(obj)) { }
or
或者
Object.values(obj).forEach(value => ...)
回答by Matt Ball
It's just a for...in
loop. Check out the documentation at Mozilla.
这只是一个for...in
循环。查看Mozilla 上的文档。
回答by JSON C11
If your environment supports ES2017then I would recommend Object.entries:
如果您的环境支持ES2017,那么我会推荐Object.entries:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});
As shown in Mozillas Object.entries()documentation:
如Mozillas Object.entries()文档所示:
The Object.entries()method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
所述Object.entries()方法返回在给定对象的自己的可枚举的属性[键,值]对的数组,在相同的顺序,通过提供一种用于... in循环(不同之处在于一个用于-in循环枚举原型链中的属性也是如此)。
Basically with Object.entries we can forgo the following extra step that is required with the older for...inloop:
基本上使用 Object.entries 我们可以放弃旧的for...in循环所需的以下额外步骤:
// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
// do stuff
}
回答by Rob Sedgwick
jquery allows you to do this now:
jquery 现在允许你这样做:
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
回答by Cyril N.
回答by dylanh724
The above answers are a bit annoying because they don't explain what you do inside the for loop after you ensure it's an object: YOU DON'T ACCESS IT DIRECTLY! You are actually only delivered the KEY that you need to apply to the OBJ:
上面的答案有点烦人,因为在确保它是一个对象后,它们没有解释您在 for 循环中所做的事情:您不直接访问它!您实际上只收到了您需要申请到 OBJ 的 KEY:
var obj = {
a: "foo",
b: "bar",
c: "foobar"
};
// We need to iterate the string keys (not the objects)
for(var someKey in obj)
{
// We check if this key exists in the obj
if (obj.hasOwnProperty(someKey))
{
// someKey is only the KEY (string)! Use it to get the obj:
var myActualPropFromObj = obj[someKey]; // Since dynamic, use [] since the key isn't literally named "someKey"
// NOW you can treat it like an obj
var shouldBeBar = myActualPropFromObj.b;
}
}
This is all ECMA5 safe. Even works in the lame JS versions like Rhino ;)
这都是 ECMA5 安全的。甚至可以在像 Rhino 这样蹩脚的 JS 版本中工作;)