javascript - 无法将对象推送到 localStorage 中的数组中

标签 javascript arrays json html local-storage

我正在尝试将 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/

相关文章:

C++无法更改数组成员

javascript - D3 JSON数据转换

java - 使用java编码的json字符串无法使用php解码

javascript - 如何将异步等待放入循环中?不工作

javascript - 网站热力图如何获取准确数据?

java - 我如何知道 Hibernate .list() 方法中的返回值是数组还是标量?

php - 使用 MYSQL 数据库中的数据绘制 google 饼图时遇到问题

javascript - Ajax执行多次

javascript - 将文本字段限制为仅数字的最佳方法?

python - 将二维数组转换为嵌套字典