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

查看:160
本文介绍了将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.

第1步:


如果您尚未在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 会话变量中存储数组。如果你已经这样做,请跳到第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步:

像这样修改你的函数:

Modify your function like so:

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天全站免登陆