从JavaScript中的对象获取值 [英] Get values from an object in JavaScript
本文介绍了从JavaScript中的对象获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个对象:
var data = {id:1,second:abcd} ;
这些是表单中的值。如果上述属性存在,我们可以通过 data [id]来获取它们的值。
data [second]
,但有时候,根据其他值,属性可能会不同。 如何从 data
获取独立于属性名称的值?
解决方案为了在不知道这些属性名称的情况下访问对象的属性,可以在循环中使用
作为... for(key in data){
if(data.hasOwnProperty(key)){
var value = data [key];
//做一些有价值的事情;
}
}
I have this object:
var data = {"id": 1, "second": "abcd"};
These are values from a form. I am passing this to a function for verification.
If the above properties exist we can get their values with data["id"]
and data["second"]
, but sometimes, based on other values, the properties can be different.
How can I get values from data
independent of property names?
解决方案 To access the properties of an object without knowing the names of those properties you can use a for ... in
loop:
for(key in data) {
if(data.hasOwnProperty(key)) {
var value = data[key];
//do something with value;
}
}
这篇关于从JavaScript中的对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文