对象数组的localStorage处理 [英] localStorage array of objects handling

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

问题描述

JSON对象的数组存储在HTML5 的localStorage 。结果
现在分隔符的 ; 结果
的localStorage 访问和修改对象的数组拆分(';')加入(';')。使用操作

Array of JSON objects are stored in HTML5 localStorage.
For now delimiter is ;
For accessing and modifying array of objects from localStorage, split(';') and join(';') operations used.

然而,分隔符方法看起来不稳定。结果
例如 ; 能在对象中得到满足的属性和斯普利特(';')操作将uncorrect。

However ,delimiter approach looks unstable.
For instance ; could be met inside objects attribute and split(';') operation will be uncorrect.

它可以用来 ;; 作为分隔符,但我不能肯定这将是稳定也。

It could be used ;; for delimiter,but i'm not certain it will be stable also.

有没有处理的localStorage presented为对象的数组,据的localStorage 保存任何可靠的方法为字符串

Is there any robust way to handle localStorage presented as array of objects,as far localStorage saved as String?

修改

塞之一,是对象的数组无法保存到localStorage的古典:[{},{}]结果
的localStorage automatially其转换为字符串如{},{}

one of stoppers is that array of object couldn't be saved to localStorage as classical: "[{},{}]"
localStorage converts it automatially to String like "{},{}"

在我的当前数据的localStorage

"{"name":"volvo","id":"033"};{"name":"saab","id":"034"}"

假设结果
也许,我可以添加 [的开始和] 结尾,但看起来并不gracefull

assumption
perhaps,i can add [ at the start and ] at the end,but it looks not gracefull

推荐答案

只需将对象转换为JSON字符串:

Just convert the objects to JSON strings:

localStorage.setItem("savedData", JSON.stringify(objects));

和反之亦然:

objects = JSON.parse(localStorage.getItem("savedData")));

或者你也可以在同一个localStorage的价值添加多个对象:

Or you can add multiple objects in the same localStorage value:

localStorage.setItem("savedData", JSON.stringify([object1, object2 /*, etc*/]));
object1 = JSON.parse(localStorage.getItem("savedData"))[0];
object2 = JSON.parse(localStorage.getItem("savedData"))[1];

这里的DOM存储规范

您也可以访问 savedData 是这样的:

You can also access savedData like this:

localStorage.savedData = "Hello world"
var foo = localStorage.savedData;

这可以同时用于获取和设置数据,但它被认为是不那么安全比的getItem('名'); setItem('名','值');

This can be used for both getting and setting the data, but it is considered less "safe" than getItem('name'); and setItem('name', 'value');

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

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