[英]How do i append an object call with a variable JS
所以問題是,我有使用window.blah.blah調用的數據,它將根據用戶或數據庫中的項目吐出信息。
現在我的問題是我想將window.blah.blah與動態附件一起使用,例如window.blah.blah.VARIABLE1
我已經嘗試過window.blah.blah.instances [variable],但是我收到一個typeerror,說未定義變量的值(因此,如果變量= test1,則錯誤為TypeError:無法讀取未定義的屬性'test1'。生成了變量。因此可以是對應於存儲對象的test1 test2。
如果有幫助的話,我正在使用它的循環中使用該調用來訪問具有不同對象名稱的存儲的json obj。
如果我的對象之一被稱為test1並且我執行window.blah.blah.test1,它也會訪問該對象,但是window.blah.blah.instances [test1]會收到上述錯誤。
我究竟做錯了什么?
也許您正在尋找的語法是window.blah.blah[VARIABLE1]
(假設blah是對象。)
請注意,將數據存儲在window上通常是一個壞主意,因此對於以下示例,我將頂級對象從全局空間(通過window
訪問)移動到局部變量中:
var myObj = {
blah: {
blah: {}
}
};
var fooVar == 'foo';
function getMyDynamicVariable() {
return "foo"; //really this would by some dynamically generated string
}
//example usage:
myObj.blah.blah[getMyDynamicVariable()];
// OR
myObj.blah.blah[fooVar];
// would be the same as
myObj.blah.blah.foo //(in this exact example, where all functions and variables contain the string 'foo'.)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.