Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果对象的名称存储为变量,是否从对象获取值?_Javascript_Json_Object - Fatal编程技术网

Javascript 如果对象的名称存储为变量,是否从对象获取值?

Javascript 如果对象的名称存储为变量,是否从对象获取值?,javascript,json,object,Javascript,Json,Object,我有一个JSON对象返回,格式如下: "miscObject": { "205": [ { "h": "Foo", "l": "Bar" } ] } miscObject包含1500多个条目,每个条目都以增量方式命名 如果在变量中存储了205,而不必遍历miscObject中的所有对象,如何才能获得'miscObject.205.h'和'miscObject.205.l'的值?使用成

我有一个JSON对象返回,格式如下:

"miscObject": {
    "205": [
        {
            "h": "Foo",
            "l": "Bar"
        }
        ]
    }
miscObject包含1500多个条目,每个条目都以增量方式命名


如果在变量中存储了205,而不必遍历miscObject中的所有对象,如何才能获得'miscObject.205.h'和'miscObject.205.l'的值?

使用成员查找语法

var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;

使用成员查找语法

var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;
看起来您谈论的是Javascript对象,而不是JSON字符串

在访问Javascript对象的属性时,x[y]和x.y通常是可互换的,区别在于前者中的y可能是一个表达式

利用这一点来解决您的问题,如:

var num = '205';
console.log(miscObject[num].l);
//                    ^^^^^
//                      \
//                     instead of `.num`, which wouldn't be the same as
//                       `num` is not the literal name of the property
看起来您谈论的是Javascript对象,而不是JSON字符串

在访问Javascript对象的属性时,x[y]和x.y通常是可互换的,区别在于前者中的y可能是一个表达式

利用这一点来解决您的问题,如:

var num = '205';
console.log(miscObject[num].l);
//                    ^^^^^
//                      \
//                     instead of `.num`, which wouldn't be the same as
//                       `num` is not the literal name of the property

使用您提到的“点”符号或使用[]可以通过两种方式访问对象值:

以下方面应起作用:

var result = miscObject["205"].h;

使用您提到的“点”符号或使用[]可以通过两种方式访问对象值:

以下方面应起作用:

var result = miscObject["205"].h;

您可以执行以下操作以获取对象:

num = '205'
miscObject[num]

您可以执行以下操作以获取对象:

num = '205'
miscObject[num]