如何在 localStorage 中存储数组? [英] How do I store an array in localStorage?
本文介绍了如何在 localStorage 中存储数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我不需要 localStorage,我的代码将如下所示:
If I didn't need localStorage, my code would look like this:
var names=new Array();
names[0]=prompt("New member name?");
这有效.但是,我需要将此变量存储在 localStorage 中,事实证明它非常顽固.我试过了:
This works. However, I need to store this variable in localStorage and it's proving quite stubborn. I've tried:
var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");
我哪里出错了?
推荐答案
localStorage
仅支持字符串.使用 JSON.stringify()
和 JSON.parse()
.
localStorage
only supports strings. Use JSON.stringify()
and JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
您也可以使用直接访问来设置/获取项目:
You can also use direct access to set/get item:
localstorage.names = JSON.stringify(names);
var storedNames = JSON.parse(localStorage.names);
这篇关于如何在 localStorage 中存储数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文