我正在制作完全离线的HTML5网络应用。
在我的代码的特定部分中,我需要向JavaScript Array对象添加一行数据,并将更新后的版本保存回localStorage
。
以下是代码:
var data = localStorage.getItem("cars");
//Trouble in this line.
data.goals.push(["name": "merscede", "model": "bmw", "noofdays": "10", "active": "yes"]);
localStorage.setItem("goals",data);
这是我在localStorage中存储的源代码的不同部分的值:
var data = '{"goals":[{"name":"rocky","model":"old","noofdays":"50","active":"no"}]}';
localStorage.setItem("goals",data);
我已经进行了广泛的故障排除,事实证明只有我特别注明的那条线路才有问题。
有什么问题?我该怎么办?
答案 0 :(得分:1)
您需要这样做:
var data = '{"goals":[{"name":"rocky","model":"old","noofdays":"50","active":"no"}]}';
localStorage.setItem("goals",data);
// You get a string when you do "getItem"
var goalsStr = localStorage.getItem("goals");
// You need to parse it.
var goalsObj = JSON.parse(goalsStr);
goalsObj.goals.push({"name": "merscede", "model": "bmw", "noofdays": "10", "active": "yes"});
console.log(goalsObj);