如何在不知道密钥的情况下访问 javascript 对象值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12344675/
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
How to access a javascript object value without knowing the key
提问by eric
Possible Duplicate:
How do I enumerate the properties of a javascript object?
可能的重复:
如何枚举 javascript 对象的属性?
If I have a javascript object like this :
如果我有一个这样的 javascript 对象:
data = {
a : 2,
b : 3
}
but a and b are arbitrary and decided at runtime. Is there any way to go through the object and access all properties without knowing the key?
但 a 和 b 是任意的,在运行时决定。有没有办法在不知道密钥的情况下遍历对象并访问所有属性?
回答by Elliot Bonneville
data = {
a : 2,
b : 3
}
for(var propName in data) {
if(data.hasOwnProperty(propName)) {
var propValue = data[propName];
// do something with each element here
}
}
回答by phenomnomnominal
Firstly, that isn't what is commonly known in JS as an Array
, it's normally known as an Object
. Array
s just contain values i.e.
首先,这不是 JS 中通常所说的Array
,它通常被称为Object
. Array
s 只包含值,即
arr = [1, 2, 3, 4]
Whereas Object
s ('Associative arrays') associate name: value pairs.
而Object
s('关联数组')关联名称:值对。
To iterate over the values of an Object
, use for...in
要迭代 an 的值Object
,请使用for...in
var object = { a: 'hello' }
for (var key in object) {
if (object.hasOwnProperty(key)) {
alert(key); // 'a'
alert(object[key]); // 'hello'
}
}
The hasOwnProperty
is important, to ensure you are only looking at the actual object, and not properties that belong to the prototype.
该hasOwnProperty
是很重要的,以确保您只着眼于实际的对象,而不是属于原型属性。