在本地存储中存储字符串列表

时间:2013-08-19 17:26:36

标签: javascript local-storage

我在浏览器中使用本地存储工作了一点。但我只使用字符串作为键值对。 有没有办法存储字符串列表(对于单个键)并读取它们?

例如说我必须在页面中显示我的朋友。如果我可以使用本地存储,我实际上不需要每次查询数据库以显示朋友列表(我知道我的应用程序会有一些不稳定的情况)。有没有办法实现这个????

提前谢谢你:)

3 个答案:

答案 0 :(得分:4)

是的 - 你可以。 localStorage只存储字符串,因此您需要将其存储为可以轻松解析的格式。

字符串列表的最简单方法是将其存储为字符串化数组。

储存:

localStorage['mylist'] = JSON.stringify(['string1', 'string2']);

装载:

var mylist = JSON.parse(localStorage['mylist']);

添加更多内容并存储:

mylist.push('newstring');
localStorage['mylist'] = JSON.stringify(mylist);

答案 1 :(得分:0)

您可以将其存储在XML文档中,也可以只使用JSON存储在任何文本文件中:http://en.wikipedia.org/wiki/JSON

答案 2 :(得分:0)

您可以将数组转换为JSON。这是一个选择。您转换然后存储为字符串,然后将其读回并转换回来。

为此,我使用了下面的几个函数,它们被调用如下:

jsonStore.putJson("friendInfo", frientInfo); // friendInfo is an object or array

var readFriendInfo = jsonStore.getJson("friendInfo");

var jsonStore = function () {
    return {
        getJson: function(key) {
            var ret = localStorage[key];
            if (ret) {
                try {
                    ret = JSON.parse(ret); // use JSON3 to handle multiple browsers/versions
                } catch (e) {
                    ret = undefined; // for parse failure
                }
            }
            return ret;
        },
        putJson: function(key, value) {
            localStorage[key] = JSON.stringify(value); // use JSON3 for this too
        }
    };
}();

同时

你可以这样做,假设关于每个朋友的字符串都在一个数组元素friendInfo中,每个索引都指示一个不同的朋友。

for (var i=0; i < friendInfo.length ; ++i) {
    localStorage.setItem("friend" + i, firentInfo[i]);
}

当我这样做时,我通常会存储另一个项目,告诉它有多少:

localStorage.setItem("friend.length", friendInfo.length);