将 JSON 对象推送到 localStorage 中的数组 [英] Push JSON Objects to array in localStorage

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

问题描述

我在 Javascript 中有一个函数:

I have a function in Javascript:

var a = [];
function SaveDataToLocalStorage(data)
{       
    var receiveddata = JSON.stringify(data);
    a.push(receiveddata);
    alert(a);

    localStorage.setItem('session', a);

}

data 参数是一个 JSON 对象.

the data parameter is a JSON Object.

但每次我点击按钮时,它都会覆盖我本地存储中的数据.

But everytime I click the button it overwrites the data in my localstorage.

有人知道怎么做吗?

推荐答案

您需要执行几个步骤才能将此信息正确存储在 localStorage 中.然而,在我们开始编写代码之前,请注意 localStorage(在当前时间)不能保存除字符串之外的任何数据类型.您需要将数组序列化以进行存储,然后将其解析回来以对其进行修改.

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

第一步:

仅当您尚未在 localStorage session 变量中存储序列化数组时,才应运行下面的第一个代码片段.
为确保正确设置 localStorage 并存储数组,请先运行以下代码片段:

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

以上代码应该只运行一次,并且仅当您尚未在 localStorage session 变量中存储 array 时.如果您已经在执行此操作,请跳至第 2 步.

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

第 2 步:

像这样修改你的函数:

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

这应该会为您处理剩下的事情.当你解析出来时,它会变成一个对象数组.

This should take care of the rest for you. When you parse it out, it will become an array of objects.

希望这会有所帮助.

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

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