Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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 it's proving quite stubborn. I've tried:

var localStorage[names] = new Array();

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

Where am I going wrong?

1 Answer

0 votes
by (40.7k points)

You can use JSON.stringify() and JSON.parse() as localStorage only supports strings

var names = [];

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

localStorage.setItem("names", JSON.stringify(names));

//...

var storedNames = JSON.parse(localStorage.getItem("names"));

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...