2012-12-24 42 views
0

我想在另一個JSON數組裏面創建一個JSON數組。
我認爲我做得對,但是當我調用第二個數組時,它返回undefined。當我調用JSON數組時返回undefined?

JSON文件:

var files = [ 
    {"Files" : [ 
     {"file1" : "file1"}, 
     {"file2" : "file2"}, 
     {"file3" : "file3"} 
    ]}, 

    {"Texts" : [ 
     {"file4" : "file4"}, 
     {"file5" : "file5"}, 
     {"file6" : "file6"} 
    ]} 
]; 

當我嘗試此命令時,它的工作原理 -

console.log(files[0]); // Works, returns the array 

但是,當我嘗試此命令時,它不工作 -

console.log(files[0][1]); // Not working, return undefined 

我期望這將返回file2。

我做錯了什麼?

編輯: 該腳本從服務器獲取類似JSON文件,腳本需要通過JSON循環。所以,想想名稱(文件,文本,文件1,文件2等)爲未知..

回答

3
console.log(files[0]["Files"]) // will return array with file 1-3 
console.log(files[0]["Texts"]) // will return array with file 4-6 

console.log(files[0].Files) // will return array with file 1-3 
console.log(files[0].Texts) // will return array with file 4-6 

在您例如files[0][1] JSON的工作,這樣

var files = [ 
    [ 
     {"file1" : "file1"}, 
     {"file2" : "file2"}, 
     {"file3" : "file3"} 
    ], 
    [ 
     {"file4" : "file4"}, 
     {"file5" : "file5"}, 
     {"file6" : "file6"} 
    ] 
]; 

編輯
在這種情況下,您可以使用下一個for-loop

for (var key in files[0]) 
{ 
    files[0][key] // here key is "Files", this will return files 1-3  
}​ 
+0

腳本從服務器獲取JSON文件那樣,和腳本需要通過JSON循環。所以想想名字是未知的。 – Israelg99

+0

@IsraelG。答案編輯 – Ilya

+0

謝謝!現在我明白了! – Israelg99

4

此:

console.log(files[0]); 

確實日誌中陣列,它是這樣的陣列的第一個元素的對象。要進入內部數組,你必須得到在該對象的「文件」屬性:

console.log(files[0].Files[1]); 

什麼將登錄不只是字符串「文件2」,但整個物體,{ file2: "file2" }。在JavaScript中,具有字符串屬性名稱的對象屬性不能通過數字索引訪問。也就是說,在對象中:

{ "foo": "hello world" } 

那裏根本就沒有[0]屬性。 JavaScript中的數組也是對象,可以有字符串命名的屬性,但它們與數字索引屬性的集合是分開的。

+0

+1擊敗了我。 – Fenton

+0

+1爲解釋! – Israelg99

2

數組是Files屬性裏面:

console.log(files[0].Files[0]); 
console.log(files[0].Files[1]);