在本地存储中存储字符串列表 [英] Storing a list of strings in local storage
问题描述
我在浏览器中处理了一些本地存储.但是我只使用字符串作为键值对. 有什么方法可以存储一个字符串列表(单个键)并读取它们??
例如,说我必须在页面中显示我的朋友.如果我可以利用本地存储,我实际上不需要每次都查询数据库来显示好友列表(我知道会有一些不稳定性,这对于我的应用程序来说是可以的).有什么办法可以做到这一点?
预先感谢您:)
是的-可以. localStorage仅存储字符串,因此您需要以一种易于解析的格式存储它.
最简单的字符串列表方法是将其存储为字符串数组.
存储:
localStorage['mylist'] = JSON.stringify(['string1', 'string2']);
正在加载:
var mylist = JSON.parse(localStorage['mylist']);
添加更多内容并存储:
mylist.push('newstring');
localStorage['mylist'] = JSON.stringify(mylist);
I worked a little bit with local storage in browsers. But i only worked with strings as key-value pair. Is there any way to store a list of strings(for a single key) and read them??
For example say I have to display my friends in a page. I actually don't need to query database every time to display the friend list if I can make use of the local storage(i know there will be some inconstancy which is OK for my application). Is there any way to achieve this????
Thank you in advance :)
Yes - you can. localStorage just stores strings, so you need to store it in a format that can be parsed easily.
Simplest approach for a list of strings would be to store it as a stringified array.
Storing:
localStorage['mylist'] = JSON.stringify(['string1', 'string2']);
Loading:
var mylist = JSON.parse(localStorage['mylist']);
Adding more and storing:
mylist.push('newstring');
localStorage['mylist'] = JSON.stringify(mylist);
这篇关于在本地存储中存储字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!