16

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=?;
Shakti Patel
  • 3,762
  • 4
  • 22
  • 29

3 Answers3

31

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"]);
Yang
  • 8,580
  • 8
  • 33
  • 58
scotty
  • 559
  • 4
  • 6
2

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"]);
0

LocalStorage can store strings and not arrays directly. Use some special symbol like '~' to concatenate the elements of array and save it as an array. When retrieving , using split('~') to get back the array.

PG1
  • 1,220
  • 2
  • 12
  • 27