将 JSON 对象推送到 localStorage 中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16083919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Push JSON Objects to array in localStorage
提问by nielsv
I have a function in Javascript:
我在 Javascript 中有一个函数:
var a = [];
function SaveDataToLocalStorage(data)
{
var receiveddata = JSON.stringify(data);
a.push(receiveddata);
alert(a);
localStorage.setItem('session', a);
}
the data parameter is a JSON Object.
数据参数是一个 JSON 对象。
But everytime I click the button it overwrites the data in my localstorage.
但是每次我单击按钮时,它都会覆盖我本地存储中的数据。
Does anybody know how to do this?
有人知道怎么做这个吗?
回答by War10ck
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) cannothold 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 中。然而,在我们深入代码之前,请注意 localStorage(在当前时间)不能保存除字符串之外的任何数据类型。您需要将数组序列化以进行存储,然后将其解析回来以对其进行修改。
Step 1:
The First code snippet below should only be run if you are not already storing a serialized array in your localStorage sessionvariable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:
第 1 步:
仅当您尚未在 localStoragesession变量中存储序列化数组时,才应运行下面的第一个代码片段。
为确保正确设置 localStorage 并存储数组,请先运行以下代码片段:
var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));
The above code should only be run onceand only if you are not already storing an arrayin your localStorage sessionvariable. If you are already doing this skip to step 2.
上面的代码只应运行一次,并且仅当您尚未在 localStorage变量中存储数组时session。如果您已经在执行此操作,请跳至第 2 步。
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.
这应该为您解决其余的问题。当你解析出来时,它会变成一个对象数组。
Hope this helps.
希望这可以帮助。
回答by techfoobar
As of now, you can only store string valuesin localStorage. You'll need to serialize the array object and then store it in localStorage.
截至目前,您只能将字符串值存储在 localStorage 中。您需要序列化数组对象,然后将其存储在 localStorage 中。
For example:
例如:
localStorage.setItem('session', a.join('|'));
or
或者
localStorage.setItem('session', JSON.stringify(a));
回答by Adrian May
Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.
将整个数组放入一个 localStorage 条目是非常低效的:每次向数组添加内容或更改条目时,都需要重新编码整个数组。
An alternative is to use http://rhaboo.orgwhich stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:
另一种方法是使用http://rhaboo.org存储任何 JS 对象,无论嵌套有多深,为每个终端值使用单独的 localStorage 条目。数组被更忠实地恢复,包括非数字属性和各种类型的稀疏性,在标准情况下恢复对象原型/构造函数,API 非常简单:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
BTW, I wrote it.
BTW,我写的。
回答by Brugolo
One thing I can suggest you is to extend the storage object to handle objects and arrays.
我可以建议你的一件事是扩展存储对象来处理对象和数组。
LocalStorage can handle only strings so you can achieve that using these methods
LocalStorage 只能处理字符串,因此您可以使用这些方法来实现
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
Using it every values will be converted to json string on set and parsed on get
使用它,每个值都将在设置时转换为 json 字符串并在获取时解析
回答by Rajesh kumar
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

