【问题标题】:Cannot push objects in array in localStorage无法在 localStorage 的数组中推送对象
【发布时间】:2014-01-23 01:26:24
【问题描述】:

我正在尝试将 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));
}

data 在哪里:

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

我收到以下错误:

 Uncaught TypeError: Cannot call method 'push' of null 

谁能展示在数组中存储 localStorage 值的正确方法?

【问题讨论】:

  • 变量“a”必须为空。在您的浏览器中使用调试器并在运行推送调用之前检查该值。我认为这应该让你走上正轨

标签: javascript arrays json html local-storage


【解决方案1】:

当您获取本地存储内容时,您将覆盖初始化“a”的初始空数组。变量被声明和初始化:

var a = [];

然后那个空数组立即被扔掉:

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

之后,如果您收到该错误,您检索到的值实际上是空的 (null)。

如果您希望“a”是或者一个新的空数组,或者是保存在本地存储中的数组,您可以这样做:

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

【讨论】:

  • @user2567857 问题可能是您实际上并没有成功保存对象。
  • 你的意思是变量data ?
  • @user2567857 否 - 如果 "a" 以 null 结尾,则意味着本地存储中没有任何具有密钥 "session" 的内容。
  • 是的,因为我正在遵循的解决方案(正如我的问题中指出的那样),首先是 getItem,然后是 setItem
  • @user2567857 OK 答案有可能扩展。
【解决方案2】:

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

【讨论】:

  • 现在它在a = JSON.parse(b); 行中显示Uncaught SyntaxError: Unexpected token H
  • var a = JSON.parse(localStorage.getItem('session')) || [];
  • 如果我先做getItem 然后setItem,那么a 仍然为空,所以我得到了错误
  • @serakfalcon 还是同样的错误,正如我指出的主要问题是先执行getItem,然后执行setItem,所以它抛出错误
  • @serakfalcon 现在显示Uncaught SyntaxError: Unexpected token else
猜你喜欢
  • 2018-07-07
  • 2013-04-11
  • 2020-10-11
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2020-12-20
相关资源
最近更新 更多