简体   繁体   中英

Using localStorage/sessionStorage to store arrays

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.

// setting values
localStorage.setItem("foo", [15,"bye"]);

// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye

// only writes the first character, instead of one part of the array 
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1

I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.

Try this:

localStorage.setItem("foo", JSON.stringify([15,"bye"]));

// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye

var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

localStorage can only store string in its value, that is why it is storing only 15;

Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"])) ;

If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));

You can parse json

let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

Or you can split by ',' and get the 0th index item.

localStorage.getItem('foo').split(',')[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM