views:

276

answers:

3

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

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

This works, however I need to store this variable in localStorage and its proving quite stubborn. I've tried:

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

Where am I going wrong?

+2  A: 

The API is .setItem() and .getItem(), but it takes a string so you'll need to .join() and .split() when pulling it in/out, like this:

var names = new Array();
names[0] = prompt("New member name?");
localStorage.setItem("names", names.join('|||'));      //some delimiter
alert(localStorage.getItem("names").split('|||')[0]);  //whatever you entered

You can give it a try here

Nick Craver
+5  A: 

localStorage only supports strings. Use JSON.stringify() and JSON.parse().

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

//...
var storedNames=JSON.parse(localStorage['names']);
no
+1  A: 

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name "three|||lines").