Reputation: 910
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.
Upvotes: 1
Views: 290
Reputation: 1526
if (localStorage.myArray) {
var myArray = localStorage.myArray.split(',');
myArray.push("Green");
localStorage.myArray = myArray;
} else {
localStorage.myArray = ["Red", "Blue"];
}
Upvotes: 0
Reputation: 33618
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"]);
}
Upvotes: 5