在localStorage的不能推在数组对象 [英] Cannot push objects in array in localStorage

查看:157
本文介绍了在localStorage的不能推在数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在存储阵列localStorage的价值,下面这个网页。推JSON对象在localStorage的阵列的。我的code是:

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

其中,数据是:

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

我收到以下错误:

I am getting the following error:

 Uncaught TypeError: Cannot call method 'push' of null 

任何人可以证明正确的方法来存储阵列localStorage的价值观?

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

推荐答案

null是对于未初始化的对象的任何一个特殊的价值。
我的猜测是localStorage.getItem(会议)是空的。

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

这篇关于在localStorage的不能推在数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆