Cannot push objects in array in localStorage

↘锁芯ラ 提交于 2020-01-02 08:13:15

问题


I am trying to store localStorage value in array and following this page Push JSON Objects to array in localStorage. My code is:

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));
}

where data is:

 var data = {name: "abc", place: "xyz"}

I am getting the following error:

 Uncaught TypeError: Cannot call method 'push' of null 

Can anybody show the correct method to store localStorage values in array?


回答1:


null is a special value for objects that aren't initialized to anything. My guess is that localStorage.getItem('session') is empty.

a more robust answer would be something like

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));
}



回答2:


You're overriding the initial empty array that initializes "a" when you fetch the local storage contents. The variable is declared and initialized:

var a = [];

and then that empty array is immediately thrown away:

a = JSON.parse(localStorage.getItem('session'));

After that, it appears that your retrieved value is actually empty (null) if you're getting that error.

If you want "a" to be either a new empty array, or else an array saved in local storage, you'd do something like this:

var a = localStorage.getItem('session') || "[]";
a = JSON.parse(a);


来源:https://stackoverflow.com/questions/20936466/cannot-push-objects-in-array-in-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!