gpt4 book ai didi

javascript 将 json 对象推送到数组

转载 作者:行者123 更新时间:2023-11-28 20:37:15 25 4
gpt4 key购买 nike

我有以下内容:

var cookie = $.cookie("Test_cookie");
var items = cookie ? eval("([" + cookie + "])") : [];
var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });

结果:

[{"packageId":"11","machineId":"1","operationType":"Download"}]

这是正确的。

但是,当我第二次运行它时,我想将新对象附加到项目中,但 json 变得困惑(注意额外的“[”):

var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });

结果:

[[{"packageId":"11","machineId":"1","operationType":"Download"}],{"packageId":"11","machineId":"1","operationType":"Download"}]

它应该是:

[{"packageId":"11","machineId":"1","operationType":"Download"},{"packageId":"11","machineId":"1","operationType":"Download"}]

什么给出了?

最佳答案

你的错误已经临近

var items = cookie ? eval("([" + cookie + "])") : [];

就这么做

var items = cookie ? eval(cookie) : [];

关于javascript 将 json 对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com