2011-06-28 137 views
32

我只是從數組,對象和JSON開始 - 希望這裏有一些簡單的東西,我可以在這裏忽略。嘗試向我的json對象中添加(推送)新項目時遇到錯誤。嵌套JSON:如何將新項目添加(推送)到對象?

我遇到以下錯誤:Result of expression 'library.push' [undefined] is not a function(朝我的代碼片段的底部)

// This is my JSON object generated from a database 
var library = { 
    "Gold Rush" : { 
     "foregrounds" : ["Slide 1","Slide 2","Slide 3"], 
     "backgrounds" : ["1.jpg","","2.jpg"] 
    }, 
    "California" : { 
     "foregrounds" : ["Slide 1","Slide 2","Slide 3"], 
     "backgrounds" : ["3.jpg","4.jpg","5.jpg"] 
    } 
} 

// These will be dynamically generated vars from editor 
var title = "Gold Rush"; 
var foregrounds = ["Howdy","Slide 2"]; 
var backgrounds = ["1.jpg",""]; 

function save() { 

    // If title already exists, modify item 
    if (library[title]) { 
     // Replace values with new 
     library[title].foregrounds = foregrounds; 
     library[title].backgrounds = backgrounds; 

     // Save to Database. Then on callback... 
     document.write('Changes Saved to <b>'+title+'</b>'); 

    // If title does not exist, add new item 
    else { 
     // Format it for the JSON object 
     var item = ('"'+title+'" : {"foregrounds" : '+foregrounds+',"backgrounds" : '+backgrounds+'}'); 


     // THE PROBLEM SEEMS TO BE HERE?? 
     // Error: "Result of expression 'library.push' [undefined] is not a function" 
     library.push(item); 


     // Save to Database. Then on callback... 
     document.write('Added: <b>'+title+'</b>'); 
    } 
} 

save(); 

回答

42

library是一個對象,而不是一個數組。你把東西推到數組上。與PHP不同,Javascript有所區別。

您的代碼嘗試創建一個看起來像鍵值對的源代碼的字符串,然後將其「推」到該對象上。這甚至不是如何工作的。

你想要做的是添加一個新的鍵值對的對象,其中關鍵是標題和值是另一個對象。看起來像這樣:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds}; 

「JSON對象」是一個模糊的術語。您必須小心區分程序中的實際內存對象和JSON格式的文本片段。

+0

完美!!謝謝! – Josiah

7

推的是一個Array方法,爲JSON對象,你可能需要將它定義

這應該這樣做:

library[title] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds}; 
+0

對!謝謝! – Josiah

11

如果你的JSON是沒有鑰匙,你可以做這樣的:

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds}; 

所以,試試這個:

var library = {[{ 
    "title"  : "Gold Rush", 
     "foregrounds" : ["Slide 1","Slide 2","Slide 3"], 
     "backgrounds" : ["1.jpg","","2.jpg"] 
    }, { 
    "title"  : California", 
     "foregrounds" : ["Slide 1","Slide 2","Slide 3"], 
     "backgrounds" : ["3.jpg","4.jpg","5.jpg"] 
    }] 
} 

Then:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]}; 
相關問題