Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array in localStorage Object in html5? [duplicate]

How to store mycars array in localStorage Object in html5?

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage.mycars=?;
like image 307
Shakti Patel Avatar asked Oct 04 '13 06:10

Shakti Patel


2 Answers

localStorage is for key : value pairs, so what you'd probably want to do is JSON.stringify the array and store the string in the mycars key and then you can pull it back out and JSON.parse it. For example,

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage["mycars"] = JSON.stringify(mycars);

var cars = JSON.parse(localStorage["mycars"]);
like image 184
scotty Avatar answered Sep 21 '22 09:09

scotty


Check his Link

http://diveintohtml5.info/storage.html

This is like a crash course for working with local storage also check this article from Mozilla Firefox

http://hacks.mozilla.org/2009/06/localstorage/

here is the official documentation for local storage

http://dev.w3.org/html5/webstorage/

Just For your problem, you can do it like this

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

var mycars = [];
localStorage["mycars"] = JSON.stringify(carnames);
var storedNames = JSON.parse(localStorage["mycars"]);
like image 29
Vinay Pratap Singh Bhadauria Avatar answered Sep 18 '22 09:09

Vinay Pratap Singh Bhadauria