我正在尝试将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值的正确方法吗?
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)); }