示例:
var myArray = ['e', {pluribus: 'unum'}];
如何获得第一个'?
我的实际数组如下所示:
({'U.S., MCC':{score:"88.88", url:"http://ati.publishwhatyoufund.org/donor/usmcc/"}, GAVI:{score:"87.26", url:"http://ati.publishwhatyoufund.org/donor/gavi/"}, 'UK, DFID':{score:"83.49", url:"http://ati.publishwhatyoufund.org/donor/ukdfid/"}, UNDP:{score:"83.38", url:"http://ati.publishwhatyoufund.org/donor/undp/"}, 'World Bank, IDA':{score:"73.81", url:"http://ati.publishwhatyoufund.org/donor/world-bank-ida/"}, 'Global Fund':{score:"70.65", url:"http://ati.publishwhatyoufund.org/donor/global-fund/"}})
我需要得到这个名字。即美国,MCC'然后得分和网址 - 我在高图中使用它作为图表中的数据点。
我知道它应该很简单,但我是一个完整的JS noob。
由于
答案 0 :(得分:4)
要从数组中获取第一个元素,只需使用:
myArray[0]
请注意0
指向数组中的第一个元素。数组是零索引的。
请查看this mdn page about arrays了解详情。
然而,你所拥有的不是数组,它是一个对象。您无法使用数字键(如0, 1, 2
等)
要获取对象的第一个元素,必须使用"键"获得该价值 假设:
var myObject = {'U.S., MCC':{score:"88.88", url:"http://ati.publishwhatyoufund.org/donor/usmcc/"}, GAVI:{score:"87.26", url:"http://ati.publishwhatyoufund.org/donor/gavi/"}, 'UK, DFID':{score:"83.49", url:"http://ati.publishwhatyoufund.org/donor/ukdfid/"}, UNDP:{score:"83.38", url:"http://ati.publishwhatyoufund.org/donor/undp/"}, 'World Bank, IDA':{score:"73.81", url:"http://ati.publishwhatyoufund.org/donor/world-bank-ida/"}, 'Global Fund':{score:"70.65", url:"http://ati.publishwhatyoufund.org/donor/global-fund/"}}
然后:
myObject['U.S., MCC']
将是:
{score:"88.88", url:"http://ati.publishwhatyoufund.org/donor/usmcc/"}
或者,作为一个更简单的例子:
var foo = {
'bar': 1,
'wut': {'nested': 'you can nest objects! (and arrays, etc)'}
baz: 'Objects, woo!', // Quotes around keys aren't mandatory, unless you have
} // spaces in the keys: 'quotes mandatory'
foo['bar'] // 1
foo.wut.nested // 'you can nest objects! (and arrays, etc)'
foo.baz // 'Objects, woo!' (you don't have to use the square brackets,
// if the key is a simple string (No spaces))
请查看this mdn article about working with objects以了解有关这些内容的更多信息。
现在,要真正得到第一个"该对象中的元素很棘手,因为对象没有排序。 (即使它们看起来如此。)
您可以使用for...in
循环浏览对象,但不保证这些项目会在不同的浏览器上以相同的顺序显示:
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) { // Make sure it's a proper element on the object, not a prototype function.
// key == ''U.S., MCC', for example,
doSomethingWith(myObject[key]);
}
}
您可以按排序顺序迭代对象,但有一些better answers out there。
答案 1 :(得分:1)
尝试使用这种情况:
var myObj = {'U.S., MCC':{score:"88.88", url:"http://ati.publishwhatyoufund.org/donor/usmcc/"}, GAVI:{score:"87.26", url:"http://ati.publishwhatyoufund.org/donor/gavi/"}, 'UK, DFID':{score:"83.49", url:"http://ati.publishwhatyoufund.org/donor/ukdfid/"}, UNDP:{score:"83.38", url:"http://ati.publishwhatyoufund.org/donor/undp/"}, 'World Bank, IDA':{score:"73.81", url:"http://ati.publishwhatyoufund.org/donor/world-bank-ida/"}, 'Global Fund':{score:"70.65", url:"http://ati.publishwhatyoufund.org/donor/global-fund/"}};
for(v in myObj) {
console.log("Obj key: "+v, myObj[v]);
}