Cannot push objects in array in localStorage

2019-05-17 08:46发布

问题:

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