我正在尝试将localStorage值存储在数组中并跟随此页面Push JSON Objects to array in 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值的正确方法吗?
答案 0 :(得分:7)
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));
}
答案 1 :(得分:1)
当您获取本地存储内容时,您将覆盖初始化“a”的初始空数组。声明并初始化变量:
var a = [];
然后立即扔掉那个空数组:
a = JSON.parse(localStorage.getItem('session'));
之后,如果您收到该错误,则检索到的值实际上是空的(null
)。
如果你想让“a” 一个新的空数组,或者保存在本地存储器中的数组,你可以这样做:
var a = localStorage.getItem('session') || "[]";
a = JSON.parse(a);