[英]How to add property to object using bracket notation for object and string for property name?
I would like to use bracket notation for writing the object name so that I can reference it via a parameter. 我想使用括号表示法来编写对象名称,以便我可以通过参数引用它。 That's fine, but I run into trouble when I try to write the property name without passing it as a parameter.
这没关系,但是当我尝试编写属性名而不将其作为参数传递时,我遇到了麻烦。 It's important that the property name is simply written out and not passed as a parameter.
简单地写出属性名称并且不作为参数传递是很重要的。 What is the correct syntax?
什么是正确的语法?
This example shows all of the syntax variations that I have tried: 此示例显示了我尝试过的所有语法变体:
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); }
As foo
is declared as a global variable, the window object will contain that object internally. 当
foo
被声明为全局变量时,window对象将在内部包含该对象。
So, you can do the following: 因此,您可以执行以下操作:
window[object]['cat'] = 5;
var foo = {}; bar('foo'); console.log('= ' + foo.cat); function bar(object) { window[object]['cat'] = 5; }
Just pass the actual object reference in: 只需传递实际的对象引用:
var foo ={} bar(foo, 'cat', 3); console.log('updated foo', foo); function bar(object, prop, val) { object[prop] = val; console.log('= ' + foo.cat); }
function bar(object, prop) {
this[object] = this[object] || {};
this[object][prop] = 5;
console.log(foo.cat)
}
hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.