簡體   English   中英

如何使用對象的括號表示法和屬性名稱的字符串向對象添加屬性?

[英]How to add property to object using bracket notation for object and string for property name?

我想使用括號表示法來編寫對象名稱,以便我可以通過參數引用它。 這沒關系,但是當我嘗試編寫屬性名而不將其作為參數傳遞時,我遇到了麻煩。 簡單地寫出屬性名稱並且不作為參數傳遞是很重要的。 什么是正確的語法?

此示例顯示了我嘗試過的所有語法變體:

 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); } 

foo被聲明為全局變量時,window對象將在內部包含該對象。

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

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

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

只需傳遞實際的對象引用:

 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)
}

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM