无法在localStorage中推送数组中的对象

use*_*857 3 javascript arrays html5 json local-storage

我正在尝试将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));
}
Run Code Online (Sandbox Code Playgroud)

在哪里data:

 var data = {name: "abc", place: "xyz"}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

 Uncaught TypeError: Cannot call method 'push' of null 
Run Code Online (Sandbox Code Playgroud)

任何人都可以显示在数组中存储localStorage值的正确方法吗?

ser*_*con 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));
}
Run Code Online (Sandbox Code Playgroud)

  • `var a = JSON.parse(localStorage.getItem('session')) || [];` (2认同)