1

I'm doing some tests with local storage. In my tests with array, i was stuck in array part (push).

What i've done:

if (localStorage.myArray) {
    localStorage.myArray.push("Green");
} else {
    localStorage.myArray = ["Red", "Blue"];
}

This returns an error:

Uncaught TypeError: localStorage.myArray.push is not a function

I know the localstorage itens are always string, but i don't know how this works in an array.

reidark
  • 870
  • 4
  • 11
  • 22
  • http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – KJYe.Name Jul 14 '15 at 14:53
  • Is `localStorage.myArray` really an Array? Try typing it in the console or looking at `localStorage.myArray.constructor` – Domino Jul 14 '15 at 14:54

2 Answers2

5

Since localStorage only takes strings, you would have to convert your arrays to JSON strings using JSON.stringify. Parse the JSON strings to array while performing further operations on the "arrays". Something like this

if (localStorage.myArray) {
    var myArray = JSON.parse(localStorage.myArray);
    myArray.push("Green");
    localStorage.myArray = JSON.stringify(myArray);
} else {
    localStorage.myArray = JSON.stringify(["Red", "Blue"]);
}
Dhiraj
  • 33,140
  • 10
  • 61
  • 78
0
if (localStorage.myArray) {
    var myArray = localStorage.myArray.split(',');
    myArray.push("Green");
    localStorage.myArray = myArray;
} else {
   localStorage.myArray = ["Red", "Blue"];
}
Darx
  • 1,516
  • 2
  • 13
  • 15