2010-05-27 55 views
25

的關聯數組我想這樣定義定義陣列

var theVar = [ 
    { "100", [0, 1, 2] }, 
    { "101", [3, 4, 5] } 
] 

基本上我希望能夠通過指定定製索引來訪問三個數字的陣列關聯數組。

但是,無論我嘗試什麼,我都無法使它工作。

我知道我可以把它定義爲:

theVar["100"] = [0, 1, 2]; 
theVar["101"] = [1, 2, 3]; 

但我設置此別的地方,我寧願要能夠把它在一個單一的聲明。

回答

31
theVar = { 
    "100": [0, 1, 2], 
    "101": [3, 4, 5] 
} 

可能會訣竅。然後您可以使用theVar["101"](或theVar[101])進行訪問。

(如vara keyword在JavaScript中,使用它作爲一個變量名是很容易造成問題。)

+0

這是* *創建關聯數組的JS版本的方式。它被稱爲對象文字符號。 – 2010-05-27 22:40:06

+0

「var」後需要一個變量或將數組名改爲非保留字 – Klaujesi 2015-08-31 13:43:50

6

看一看的JSON語法,我覺得它可以激發你的數據結構的建設按照您想要的方式靈活,正確和複雜。

This頁面有很多信息和示例對您有所幫助。

例如看看這個:

var employees = { "accounting" : [ // accounting is an array in employees. 
            { "firstName" : "John", // First element 
             "lastName" : "Doe", 
             "age"  : 23 }, 

            { "firstName" : "Mary", // Second Element 
             "lastName" : "Smith", 
             "age"  : 32 } 
            ], // End "accounting" array.         
        "sales"  : [ // Sales is another array in employees. 
            { "firstName" : "Sally", // First Element 
             "lastName" : "Green", 
             "age"  : 27 }, 

            { "firstName" : "Jim", // Second Element 
             "lastName" : "Galley", 
             "age"  : 41 } 
            ] // End "sales" Array. 
       } // End Employees 
+6

這不是JSON。這是對象文字符號--JSON是**的子集**。 能夠調用任何JSON的第一個前提是它包含在**字符串**中。 ;) – 2010-05-27 22:38:50

+0

對我來說看起來像JSON。屬性名稱必須是正確的JSON字符串,但值不能。還是有什麼你的意思? – rob 2010-05-28 01:10:10

+1

看看這裏:http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation – 2013-12-11 12:59:26