一尘不染

JavaScript如何在localStorage中存储阵列?

javascript

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

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

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

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

我要去哪里错了?


阅读 333

收藏
2020-04-25

共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-04-25