Tôi chỉ mới bắt đầu với Mảng, Đối tượng và JSON - vì vậy hy vọng chỉ có một cái gì đó đơn giản mà tôi nhìn thấy ở đây. Tôi gặp phải lỗi khi cố gắng thêm (đẩy) một mục mới vào đối tượng json của tôi.JSON lồng nhau: Cách thêm (đẩy) các mục mới vào một đối tượng?
Tôi gặp phải lỗi sau: Result of expression 'library.push' [undefined] is not a function
(về phía cuối đoạn mã của tôi).
// 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();
Hoàn hảo !! Cảm ơn! – Josiah