JavaScript按对象值访问数组元素

时间:2015-05-12 14:43:31

标签: javascript arrays

如果我有一组这样的键/值对:

WX Code     WMO WX Code Description
-------     -----------------------
00      No significant weather
04      Haze
10      Mist
20      Fog detected in last hour
21      Precip detected in last hour
22      Drizzle detected in last hour
23      Rain detected in last hour
24      Snow detected in last hour

我希望通过整数代码作为数组访问,格式化数组的最佳方法是什么? 如果我试试这个

var arrWXcodes = [
{00:"No significant weather"},
{04:"Haze"},
{10:"Mist"},
{20:"Fog detected in last hour"},
{21:"Precip detected in last hour"},
{22:"Drizzle detected in last hour"},
{23:"Rain detected in last hour"},
{24:"Snow detected in last hour"}];

我尝试访问阵列来获取,说" Haze"像这样,我不能得到我想要的东西。我想通过键的整数值访问数组,而不是数组中的位置

arrWXcodes["04"]
undefined
arrWXcodes[04]
Object { 21: "Precip detected in last hour" }

能够使用整数键访问数组并获得预期值的最佳数据结构和访问方法是什么?

2 个答案:

答案 0 :(得分:8)

删除对象数组,只有一个主对象:

var arrWXcodes = {
    "00": "No significant weather",
    "04": "Haze",
    ...
}

然后,您可以使用arrWXcodes["00"]

来访问这些属性

在传入整数时,您在自己的代码中获得的结果与预期不同的原因是因为这样做会引用数组的索引而不是属性名称。上例中的0"No significant weather",而"Haze"1而非4。索引4(数组中的第5项)是您的对象,其值为"Precip detected in last hour"

如果您真的希望能够使用整数访问值,可以使用"" + 4将数字转换为字符串,但这会生成"4"而不是"04",因此,如果您的密钥名称属于该结构,则需要实现以下内容:How can I pad a value with leading zeros?

答案 1 :(得分:0)

基本上,您正在定义一个对象数组。如果你通过索引04去了第5个元素:{21:"Precip detected in last hour"}。并且索引"04"未在数组中定义。 Array类似于具有整数键及其值的对象:arrWXcodes={0:{00:"No significant weather"},1:{04:"Haze"}...}

您应该使用对象

,而不是使用数组
arrWXcodes={
    "00":"No significant weather",
    ....
};