javascript 向 JSON 添加一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11181058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:18:17  来源:igfitidea点击:

Adding a row to JSON

javascriptjqueryjson

提问by Jason Wells

I want to add a new row to my JSON when the user clicks a link. Here's my javascript: It's not erroring, but I am not getting updated JSON in my alert.

当用户单击链接时,我想在我的 JSON 中添加一个新行。这是我的 javascript:它没有出错,但我的警报中没有更新 JSON。

$(document).ready( function(){

people = {
    "COLUMNS":["NAME","AGE"],
    "DATA":[
    ["Jon","16"],
    ["Jerry","23"]
    ]
} 

members = people.DATA;
var nc = "<table border=1 width=500><tr><td>name</td><td>age</td><td></td></tr>";

for(var i=0;i<members.length;i++)
{
    nc+= '<tr><td>' + members[i][0] + '</td>';
    nc+= '<td>' + members[i][1] + '</td>';
    nc+= '<td><a href="" class="addlink">add a new person</a></td></tr>';
}

nc += "</table>";

$("#result").html(nc);

$(".addlink").click( function(){ 

    // add another row to our JSON
    people.DATA['NAME'] = "new";
    people.DATA['AGE'] = "99";

    alert(people.DATA);
    return false;

});
});

回答by Guffa

That's not JSON, it's a Javascript object.

那不是 JSON,它是一个 Javascript 对象。

To add another item in the array, you create an array and add to it, as it is an array of arrays:

要在数组中添加另一个项目,请创建一个数组并将其添加到其中,因为它是一个数组数组:

people.DATA.push(["new", "99"]);