Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store an array in localStorage? [duplicate]

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?

like image 427
David Avatar asked Jul 28 '10 21:07

David


People also ask

Can you save an array to localStorage?

Save Array In localStorageYou can save the array by using the setItem method. const myBlogs = ["https://catalins.tech", "https://exampleblog.com"]; localStorage. setItem('links', JSON. stringify(myBlogs));

Do we need to Stringify the array before storing into local storage?

In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.

How store array in local storage in react?

Use localStorage. setObj(key, value) to save an array or object and localStorage. getObj(key) to retrieve it. The same methods work with the sessionStorage object.

How do I store multiple values in localStorage?

You can store the value in localStorage with the key value pair. It has two methods setItem(key, value) to store the value in the storage object and getItem(key) to retrieve the value from the storage object. document. getElementById("result").


1 Answers

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

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

You can also use direct access to set/get item:

localstorage.names = JSON.stringify(names); var storedNames = JSON.parse(localStorage.names); 
like image 158
Dagg Nabbit Avatar answered Sep 27 '22 22:09

Dagg Nabbit