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?
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));
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.
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.
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").
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With