【问题标题】:Get value of variable in order to get value from dictionary in javascript获取变量的值以便从 javascript 中的字典中获取值
【发布时间】:2013-06-23 00:06:24
【问题描述】:

我有一个大的 JSON 字符串,我已将其编码为 javascript 对象。看起来是这样的:

{"stdout": "", 
"line": 23, 
"func_name": "<module>", 
"stack_to_render": [
    {"is_parent": true, 
    "ordered_varnames": ["__init__", "__qualname__", "num", "player", "__return__"], 
    "is_zombie": true, 
    "encoded_locals": {"__qualname__": "Team", "player": ["REF", 3], "__init__": ["REF", 2], "__return__": ["REF", 1], "num": 5}, 
    "frame_id": 1, 
    "unique_hash": "Team_f1_p_z", 
    "func_name": "Team", 
    "is_highlighted": false, 
    "parent_frame_id_list": []}], 
"ordered_globals": ["Team", "i_type", "s_type", "l_type", "t_type", "d_type",         "o_type", "make_squares"], 
"globals": {"s_type": "hello", 
    "o_type": ["REF", 8], 
    "l_type": ["REF", 5], 
    "make_squares": ["REF", 9], 
    "Team": ["REF", 4], 
    "d_type": ["REF", 7], 
    "i_type": 3, 
    "t_type": ["REF", 6]}, 
"heap": {"1": ["DICT", 
            ["__qualname__", "Team"], 
            ["player", ["REF", 3]], 
            ["__init__", ["REF", 2]], 
            ["num", 5]
          ], 
    "2": ["FUNCTION", "__init__(self)", 1], 
    "3": ["FUNCTION", "player(self, name)", 1], 
    "4": ["CLASS", "Team", [], ["__init__", ["REF", 2]], 
            ["__qualname__", "Team"], ["num", 5], ["player", ["REF", 3]]], 
    "5": ["LIST", 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    "6": ["TUPLE", 2, 3], 
    "7": ["DICT", ["dictionary", 1]], 
    "8": ["INSTANCE", "Team", ["logo", null], ["members", 0]], 
    "9": ["FUNCTION", "make_squares(key, value)", null]}, 
"event": "return"}]}'

比方说,

var dict = "That dictionary ^^"

我有以下代码:

var name = dict.ordered_globals[i]; //Let's say returns "Team"

var ref = dict.globals.name;        
alert(ref[1]); //Should alert 4`

它抛出 undefined 因为字典中没有 .name 键值。 我想要它做的是将dict.globals.name 视为dict.globals.Team

【问题讨论】:

    标签: javascript json dictionary


    【解决方案1】:

    你需要做的:

    var ref = dict.globals[name]
    

    否则,name 将被视为文字键,而不是存储在 name 变量中的字符串。你想要后者。

    【讨论】:

      【解决方案2】:

      如果您使用var ref = dict.globals.name;,它会将name 视为dict.globals 的属性之一,但dict.globals 根本没有name 属性,以防您想检索一个对象的属性,但您不确切知道属性名称,或者它可以在运行时更改,如果是这种情况,那么文字键就会出现var ref = dict.globals[name]。希望对您有所帮助

      【讨论】:

        猜你喜欢
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 2022-12-17
        相关资源
        最近更新 更多