This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
我正在尝试使用字符串中包含的属性值动态访问对象。下面的例子:

var toolState = {
    draw_point: false;
    draw_line: false;
}

var dynamicText = "draw_point";

toolState.dynamicText = true; //here is the problem


我是JS的新手。抱歉,这是一个愚蠢的问题。

谢谢

最佳答案

对于变量名称作为属性,请使用方括号符号代替点符号。

toolState[dynamicText] = true;

10-01 01:26