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

 灬丶领袖 发布于 2023-02-06 13:48

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

在哪里data:

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

我收到以下错误:

 Uncaught TypeError: Cannot call method 'push' of null 

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

1 个回答
  • 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));
    }
    

    2023-02-06 13:52 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有