如何使用对象的方括号符号和属性名称的字符串为对象添加属性?

时间:2019-04-03 19:14:46

标签: javascript object syntax parameters notation

我想使用括号表示法来写对象名称,以便可以通过参数引用它。很好,但是当我尝试编写属性名称而不将其作为参数传递时,我遇到了麻烦。重要的是,必须简单地写出属性名称,并且不要将其作为参数传递。正确的语法是什么?

此示例显示了我尝试过的所有语法变体:

var foo = {};

bar('foo', 'cat');
function bar(object, prop) {
    
    // foo[prop] = 5; // = 5. This works, but this isn't the method I want to use. 
    
    // [object]cat = 5; // = error
    // [object].cat = 5; // = undefined
    // [object]['cat'] = 5; // = undefined
    // [object][cat] = 5; // = error
    
    console.log('= ' + foo.cat);
}

3 个答案:

答案 0 :(得分:1)

由于foo被声明为全局变量,因此窗口对象将在内部包含该对象。

因此,您可以执行以下操作:

window[object]['cat'] = 5;

var foo = {};

bar('foo');
console.log('= ' + foo.cat);
function bar(object) {
    window[object]['cat'] = 5;            
}

答案 1 :(得分:0)

只需在以下位置传递实际的对象引用:

var foo ={}

bar(foo, 'cat', 3);

console.log('updated foo', foo);

function bar(object, prop, val) {
    object[prop] = val;      
    console.log('= ' + foo.cat);
}

答案 2 :(得分:-1)

function bar(object, prop) {
  this[object] = this[object] || {};
  this[object][prop] = 5;
  console.log(foo.cat)
}

希望这会有所帮助!