我只是从数组、对象和JSON开始——希望这里有一些简单的东西我忽略了.我在try 向json对象中添加新项时遇到错误.

I'm encountering the following error: Result of expression 'library.push' [undefined] is not a function (towards the bottom of my code snippet).

// 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();

推荐答案

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

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

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

Json相关问答推荐

SWIFT中的网络经理

从json数组中删除特定元素

写入JSON文件的流

处理输入数据并转换为更简单的格式-PowerBI

对一些JSON模式验证的混淆

使用JQ合并JSON列表中的对象

如何使用 jq 将字符串数组转换为对象?

将 JSON 解组为具有唯一元素的 map 切片

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

传统编程语言等价于动态 SQL

如何使用 jq 返回此 JSON 文件的文本字段?

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

将json字符反序列化为枚举

使用 GSON 解析嵌套的 JSON 数据

在浏览器中查看 JSON 文件

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性

Laravel 5 控制器将 JSON 整数作为字符串发送

Java HashMap 与 JSONObject

如何从 github API 解析链接头