Javascript 按键获取Javascript对象值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6650587/
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 22:37:50  来源:igfitidea点击:

Get Javascript object value by key

javascript

提问by John Cooper

var Array = [];

{'DateOfBirth' : '06/11/1978',
 'Phone' : '770-786',
 'Email' : '[email protected]' ,
 'Ethnicity' : 'Declined' ,
 'Race' : 'OtherRace' , }

I need to access the 'Race' here.. how can i do it... Its an array which holds this data...

我需要在这里访问“比赛”……我该怎么做……它是一个保存这些数据的数组……

回答by minichate

Thats not an array, its an object. You want to do something like:

那不是一个数组,它是一个对象。你想做这样的事情:

var myObject = {
  'DateOfBirth' : '06/11/1978',
  'Phone' : '770-786',
  'Email' : '[email protected]' ,
  'Ethnicity' : 'Declined' ,
  'Race' : 'OtherRace'
};

// To get the value:
var race = myObject.Race;

If the Objects are inside an array var ArrayValues = [{object}, {object}, ...];then regular array accessors will work:

如果对象在数组内,var ArrayValues = [{object}, {object}, ...];则常规数组访问器将起作用:

var raceName = ArrayValues[0].Race;

var raceName = ArrayValues[0].Race;

Or, if you want to loop over the values:

或者,如果您想遍历这些值:

for (var i = 0; i < ArrayValues.length; i++) {
    var raceName = ArrayValues[i].Race;
}

Good documentation for arrays can be found at the Mozilla Developer Network

可以在Mozilla 开发人员网络上找到有关数组的良好文档

回答by pimvdb

A few things here.

这里有几件事。

You do not use Array, moreover, Arrayis actually what you can call when creating an Array, which you overwrite.

Array此外,您不使用,Array实际上是您在创建 时可以调用的Array,您可以覆盖它。

Second, you have an object({...}), but you do not assign it to something. Do you perhaps want to store it in a variable? (var obj = {...})?

其次,您有一个object( {...}),但您没有将它分配给某个东西。您可能想将其存储在变量中吗?( var obj = {...})?

Thirdly, the last ,should not be there since there aren't any more elements.

第三,最后一个,不应该在那里,因为没有更多的元素。

If you have stored it in a variable, you can access it like obj.Race.

如果您已将其存储在变量中,则可以像obj.Race.

回答by Jules

var myObject = {
  'DateOfBirth' : '06/11/1978',
  'Phone' : '770-786',
  'Email' : '[email protected]' ,
  'Ethnicity' : 'Declined' ,
  'Race' : 'OtherRace'
};

// To get the value:
var race = myObject.Race;
//or
var race = myArray[index].Race;