JavaScript按对象值访问数组元素 [英] JavaScript access array elements by object value

查看:80
本文介绍了JavaScript按对象值访问数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a set of key/value pairs like this:

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

,格式化该格式的最佳方法是什么数组?
如果我尝试这样做

that I want to access as an array by the integer code, what is the best way to format the array? If I try this

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"}];

然后我尝试访问数组,像这样说阴霾,我不得到我想要的。我想通过键的整数值而不是数组中的位置访问数组

And I try to access the array to get, say "Haze" like so, I don't get what I want. I want to access the array by the key's integer value, not the position in the array

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

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

What would be the best data structure and access method to be able to use an integer key to access the array and get the expected value?

推荐答案

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

Drop the array of objects and just have one main object:

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

然后可以使用 arrWXcodes [ 00] 等访问它们的属性。

You can then access them properties by using arrWXcodes["00"], etc.

传入整数时,得到的结果与您自己的代码中的预期结果不同的原因是,这样做将引用数组的索引而不是属性名。上例中的 0 没有明显的天气 ,而阴霾 1 而不是 4 。索引 4 (数组的第5个项目)是值为最近一小时检测到的沉淀 的对象。

The reason you get a different result than expected in your own code when passing in an integer is because doing this references the index of the array and not the property name. 0 in the above example is "No significant weather", whereas "Haze" is 1 and not 4. Index 4 (the 5th item in the array) is your object with the value "Precip detected in last hour".

如果您确实希望能够使用整数访问值,则可以使用 + 4 <将数字转换为字符串/ code>,但这将生成 4 而不是 04 ,因此如果您输入密钥名称位于该结构中,您需要实现以下内容:如何用前导零填充值?

If you really want to be able to access the values with an integer you can convert the number to a string by using "" + 4, however this will generate "4" and not "04", so if your key names are in that structure you'd need to implement something like this: How can I pad a value with leading zeros?

这篇关于JavaScript按对象值访问数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆