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

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

问题描述

JSON 对象数组存储在 HTML5 localStorage 中.
现在分隔符是 ;
用于访问和修改来自 localStoragesplit(';')join(';') 操作的对象数组.

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.

然而,分隔符方法看起来不稳定.
例如;可以在objects属性内满足,split(';')操作将不正确.

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,就 localStorage 保存为 String 而言?

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

编辑

一个阻碍是对象数组不能像经典那样保存到 localStorage:"[{},{}]"
localStorage"{},{}"

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

我在 localStorage 中的当前数据:

my current data within localStorage:

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

假设
也许,我可以在开头添加 [ 并在末尾添加 ],但它看起来不太优雅

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:

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

这可以用于获取和设置数据,但它被认为不如 getItem('name');setItem('name', 'value');

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