javascript 访问javascript字典时作为变量的键

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

key as variable when accessing javascript dictionary

javascriptvariablesdictionarykey

提问by user1952949

i am trying to store css values for transformations of multiple divs in a dictionary to access them when the div is clicked (the div id being the key of the dict).

我试图在字典中存储多个 div 转换的 css 值,以便在单击 div 时访问它们(div id 是 dict 的键)。

my dictionary:

我的字典:

css_dict = {
    'keyA' : ['10px, 15px', '20px', '10px'],
    'keyB' : ['20px, 30px', '10px', '20px'],
    'keyA' : ['30px, 55px', '25px', '30px'],
}

i need to access it like this (variable instead of the key):

我需要像这样访问它(变量而不是键):

css_dict.var[0]

jsFiddle of what im trying to do: http://jsfiddle.net/tKFka/25/

我正在尝试做的 jsFiddle:http: //jsfiddle.net/tKFka/25/

i cant figure out or find the right syntax for this to work...

我无法弄清楚或找到正确的语法来让它工作......

回答by Marius Bal?ytis

Use []instead of dot.

使用[]代替点。

var var1 = 'keyA';
css_dict[var1][0];