如何在不知道密钥的情况下访问 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:46:11  来源:igfitidea点击:

How to access a javascript object value without knowing the key

javascript

提问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. Arrays just contain values i.e.

首先,这不是 JS 中通常所说的Array,它通常被称为Object. Arrays 只包含值,即

arr = [1, 2, 3, 4]

Whereas Objects ('Associative arrays') associate name: value pairs.

Objects('关联数组')关联名称:值对。

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 hasOwnPropertyis important, to ensure you are only looking at the actual object, and not properties that belong to the prototype.

hasOwnProperty是很重要的,以确保您只着眼于实际的对象,而不是属于原型属性。