我只是从数组、对象和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相关问答推荐

Servicestack 返回数组而不是带有数组的对象

如何在 Django 的模板语言中获取 json 键和值?

漂亮的打印 JSON 转储

java.lang.BootstrapMethodError:调用站点#4 bootstrap 方法的异常,初始化改造时

在 pandas DataFrame 中取消嵌套(分解)多个列表列的有效方法

有没有办法在 angular.json 中扩展配置?

dotnet core System.Text.Json unescape unicode 字符串

错误:List 不是 Map 类型的子类型

将 YAML 文件转换为 Python JSON 对象

type 'List' 不是 type 'List' 的子类型,其中

将对象转换为可编码对象失败

使用Angular 2 的 http.get() 从本地文件加载 json

如何删除json对象键和值.?

没有从字符串值('')反序列化的字符串参数构造函数/工厂方法

json.loads 可以忽略尾随逗号吗?

使用 JSONEncoder 编码/解码符合协议的类型数组

Swift 中对象的自动 JSON 序列化和反序列化

react 路由 v^4.0.0 未捕获类型错误:无法读取未定义的属性“位置”

新的@angular/cli 版本中的文件 angular-cli.json 在哪里?

在 React 中访问子级的父级状态