简体   繁体   English

如何使用对象的括号表示法和属性名称的字符串向对象添加属性?

[英]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.

相关问题 javascript 中的括号符号如何访问 object 的属性? - How bracket notation in javascript access the property of an object? 如何使用['key']表示法向对象添加属性? - How to add a property to an object using the ['key'] notation? 无法使用“ .nested”标志和括号表示法检查嵌套对象的属性 - Unable to check a nested object property by using the “.nested” flag and bracket notation 使用括号符号(带有变量)访问对象属性的好处 - Benefit of using bracket notation (with variables) to access a property of an object 使用带有变量的括号表示法来访问 object 属性返回未定义 - Using bracket notation with a variable to access object property returns undefined 使用括号符号访问Javascript对象的属性 - Accessing a property of a Javascript object with bracket notation 在angular中,如何通过模板内的括号表示法访问对象属性? - In angular, how to access object property via bracket notation inside templates? 实现一个函数来访问对象的属性,而不是使用点符号或方括号符号来访问属性? - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation? 在 JavaScript 中,是否有任何方法可以在不使用点符号或括号符号的情况下获取 object 的属性? - In JavaScript, do there exist any ways to get a property of an object without using dot notation or bracket notation? 无法使用点符号或索引器符号向对象添加属性? - Unable to add a property to an object using either the dot notation or the indexer notation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM