This question already has answers here:
Dynamically access object property using variable
                                
                                    (13个回答)
                                
                        
                                5年前关闭。
            
                    
我想使用以下函数setDef()设置变量。

我的例子不起作用。我该怎么办?

    var defs = {
      title: document.title,
      action:   "pageview"
    };

    var setDefs = function(a,b) {
       defs.a= b;     // this: defs.title = b; is working.
    };

    setDefs("title","test");

最佳答案

使用括号符号object[variable]代替:

var setDefs = function(a,b) {
       defs[a] = b;
};


同样更适合在对象中包含此方法:

var defs = {
      title: document.title,
      action:   "pageview",
      setDefs: function(a,b) {
       this[a] = b;
      }
};

defs.setDefs("title","test");

// > defs
// Object {title: "test", action: "pageview", setDefs: function}

关于javascript - 用函数设置变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25313368/

10-09 13:42