HTML5 localStorage 设计问题
在 HTML5 的 localStorage 中存储对象数据的最佳方式是什么?我对键值存储没有做过太多研究。
在我的研究中,我看到了几种不同的方法。
示例数据:
var commands = [
{invokes: 'Window', type: 'file', data: '/data/1'},
{invokes: 'Action', type: 'icon', data: '/data/2'},
{invokes: 'Window', type: 'file', data: '/data/3'}
];
方法 1:存储代表每个数据项的键
// for(...) {
localStorage["command[" + i + "].invokes"] = command[i].invokes
localStorage["command[" + i + "].type"] = command[i].type
localStorage["command[" + i + "].data"] = command[i].data
//}
方法 2:键是实体名称,存储 json
localStorage["commands"] = JSON.stringify(commands);
第二种方法需要 JSON.parse()。
优点/缺点?
What is the best way to store object data in HTML5's localStorage. I haven't worked much with key value storage.
In my research i've seen a few different approaches.
example data:
var commands = [
{invokes: 'Window', type: 'file', data: '/data/1'},
{invokes: 'Action', type: 'icon', data: '/data/2'},
{invokes: 'Window', type: 'file', data: '/data/3'}
];
Approach 1: store keys that represent each data item
// for(...) {
localStorage["command[" + i + "].invokes"] = command[i].invokes
localStorage["command[" + i + "].type"] = command[i].type
localStorage["command[" + i + "].data"] = command[i].data
//}
Approach 2: keys is entity name, store json
localStorage["commands"] = JSON.stringify(commands);
Second approach would require a JSON.parse().
pros/cons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为记录,我使用了方法 2。我的键类似于表名,值是记录的 json 字符串数组。检索表时,您必须调用 JSON.parse()。
For the record I went with approach 2. My key is similar to a table name, the value is a json stringified array of records. When retrieving the table you must call JSON.parse().
本地存储的技术是: http://madhukaudantha .blogspot.com/2011/02/client-side-storages-with-html-5.html...
方法2,好的..
还有更多方法
technologies for local storages are: http://madhukaudantha.blogspot.com/2011/02/client-side-storages-with-html-5.html...
Approach 2, OK..
there are more ways
当然,你的方法效果很好,但它确实让你有点坚持你选择的前进惯例。我建议您考虑将 localStorage 访问包装在一个类中,以便您的约定作为真正的约定与类隔离。
否则,如果你选择改变你的方法,你的实现代码将会分散在你的代码库中。
Certainly your approach works just fine however it does leave you a bit stuck with the convention you chose moving forward. I would recommend that you consider wrapping your localStorage access up in a class so that your convention is isolated to a class as a true convention.
Otherwise should you chose to change ho you approach it you will have implementation code scattered all over your code base.