I am trying to use localStorage to save an array of strings. I have a function addToFav(string)
which is meant to load the string value into an array which holds program names, or pNames in my case. I'm trying to follow this outline: How do I store an array in localStorage?
localStorage.arrayNum = 0;
var pNames=[];
function addToFav(string)
{
pNames[localStorage.arrayNum] = string;
if (localStorage.arrayNum)
{
localStorage.arrayNum=Number(localStorage.arrayNum)+1;
}
else
{
localStorage.arrayNum=1;
}
localStorage['pNames']=JSON.stringify(pNames);
var storedNames=JSON.parse(localStorage['pNames']);
document.getElementById("testField").innerHTML=storedNames;
}
When I click the button that invokes addToFav(string)
, the string that I passed into the function is displayed in the testfield div, which is OK. However, launching the function again should add another element to the array but it doesn't, it just repeatedly adds to pNames[0] which is because I think that the pNames
and arrayNum
are getting redeclared everytime. With this, does anyone know how to prevent this problem? I would like to create an array that adds favourite items when the user invokes my function.
Thanks!