小编典典

如何在localStorage中存储阵列?

html

如果我不需要localStorage,我的代码将如下所示:

var names=new Array(); 
names[0]=prompt("New member name?");

这可行。但是,我需要将此变量存储在localStorage中,事实证明它很顽固。我试过了:

var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");

我要去哪里错了?


阅读 363

收藏
2020-05-10

共1个答案

小编典典

localStorage仅支持字符串。使用JSON.stringify()JSON.parse()

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));
2020-05-10