HTML5 localStorage 设计问题

发布于 2024-09-25 10:48:05 字数 711 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

童话里做英雄 2024-10-02 10:48:05

作为记录,我使用了方法 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().

夢归不見 2024-10-02 10:48:05

本地存储的技术是: 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

苹果你个爱泡泡 2024-10-02 10:48:05

当然,你的方法效果很好,但它确实让你有点坚持你选择的前进惯例。我建议您考虑将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文