Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - 如何在localStorage中存储阵列? [重复](How do I store an array in localStorage? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

If I didn't need localStorage, my code would look like this:

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

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

This works.

(这可行。)

However, I need to store this variable in localStorage and it's proving quite stubborn.

(但是,我需要将此变量存储在localStorage中,事实证明它很顽固。)

I've tried:

(我试过了:)

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

Where am I going wrong?

(我要去哪里错了?)

  ask by David translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

localStorage only supports strings.

(localStorage仅支持字符串。)

Use JSON.stringify() and JSON.parse() .

(使用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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...