javascript json 键作为数字

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

json keys as numbers

javascriptjson

提问by Jeffz

I have a JSON passed to script. I do not know JSON keys as they are dynamic.

我有一个 JSON 传递给脚本。我不知道 JSON 键,因为它们是动态的。

Actually, they are numbers. That's what I'm getting.

实际上,它们是数字。这就是我得到的。

var countries = {"223":"142,143","222":"23,26,25,24","170":"1,2"};

I tried to access data like this:

我试图访问这样的数据:

var objKey = 223;  (var objKey = "223";)
countries.objKey;

I tried changing JSON to

我尝试将 JSON 更改为

var countries = {"country223":"142,143","country222":"23,26,25,24","country170":"1,2"};

... and access it like this:

...并像这样访问它:

var objKey = "country"+223; (var objKey = "country"+"223";)
countries.objKey;

... again nothing.

……又没什么。

Any advice would be greatly appreciated.

任何建议将不胜感激。

回答by user113716

Instead of this:

取而代之的是:

countries.objKey;

Do this:

做这个:

 countries[objKey];

With square bracket notation, you can use the value referenced in a variable (or use a string or number) to reference the property name.

使用方括号表示法,您可以使用变量中引用的值(或使用字符串或数字)来引用属性名称。