无法将数组中的对象推送到 localStorage 中
2014-01-05
7285
我尝试将 localStorage 值存储在数组中,并按照此页面 将 JSON 对象推送到 localStorage 中的数组 。我的代码是:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session'));
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
其中
data
是:
var data = {name: "abc", place: "xyz"}
我收到以下错误:
Uncaught TypeError: Cannot call method 'push' of null
有人可以展示将 localStorage 值存储在数组中的正确方法吗?
2个回答
null 是未初始化任何内容的对象的特殊值。 我猜 localStorage.getItem('session') 是空的。
更可靠的答案应该是这样的
function SaveDataToLocalStorage(data)
{
var a;
//is anything in localstorage?
if (localStorage.getItem('session') === null) {
a = [];
} else {
// Parse the serialized data back into an array of objects
a = JSON.parse(localStorage.getItem('session'));
}
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
serakfalcon
2014-01-05
您正在覆盖在获取本地存储内容时初始化“a”的初始空数组。变量已声明并初始化:
var a = [];
然后该空数组立即被丢弃:
a = JSON.parse(localStorage.getItem('session'));
之后,如果您收到该错误,则似乎您检索到的值实际上为空 (
null
)。
如果您希望“a” 要么 是一个新的空数组,要么是保存在本地存储中的数组,您可以执行以下操作:
var a = localStorage.getItem('session') || "[]";
a = JSON.parse(a);
Pointy
2014-01-05