2014-09-26 48 views
-3

我有以下對象添加數值命名元素的一個對象在JavaScript

var foo = { 
    "1" : { 
     "test1" : "this is a test", 
     "test2" : "this is a test2" 
    } 
} 

你如何能夠插入另一個數字命名的元素?

"2" : { 
     "test3" : "this is a test3", 
     "test4" : "this is a test4" 
    } 
+0

您已經嘗試了什麼?請注意,這個答案依賴於你知道JS對象的訪問方法。那裏有兩個。 – Andy 2014-09-26 14:41:12

+0

我試過foo.1 = {};和foo。「1」= {};但肯定是行不通的。如何將數字編號作爲屬性名稱? – Jigs 2014-09-26 14:49:53

+0

@FelixKling,這不是重複的。 – Andy 2014-09-26 15:03:50

回答

2

您可以使用點或方括號表示訪問該對象。在這種情況下,您需要使用方括號表示法:

foo['2'] = { 
    test3: "this is a test3", 
    test4: "this is a test4" 
}