我正在尝试将 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));
}
数据
是:
var data = {name: "abc", place: "xyz"}
我收到以下错误:
Uncaught TypeError: Cannot call method 'push' of null
谁能展示在数组中存储 localStorage 值的正确方法?
最佳答案
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));
}
关于javascript - 无法将对象推送到 localStorage 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20936466/