1

I'm trying to push

titles.push(title);

but there's an error when I try to run it: titles.push is not a function.

Full code:

    var title = prompt("What would you like your title to be?");
        localStorage.setItem(title, editElem.innerHTML); 
    var titles = localStorage.getItem("titles");
        if(titles == null) 
            titles = new Array();
        if(titles.indexOf(title) < 0) 
            titles.push(title); 
        localStorage.setItem("titles", titles); 
    }
cosmo
  • 751
  • 2
  • 14
  • 42
  • could you also mention what `title` is in your code? By the looks of it, title is not defined. Other than that, the code looks fine. – Aakash Sigdel Jul 27 '16 at 01:59
  • 1
    localStorage do not support storing arrays. Check this link: http://stackoverflow.com/questions/3357553/how-to-store-an-array-in-localstorage –  Jul 27 '16 at 02:03
  • To use the push function of an Array your variable needs to be an Array. Looks like in your case the type of your variable isn't what you think it is. – Freelex Jul 27 '16 at 02:12
  • I declared titles = new Array(); though, doesn't that make my variable an array? – cosmo Jul 27 '16 at 02:13

1 Answers1

0

Local Storage can only store strings, not arrays:

localStorage.setItem(keyName, keyValue);

keyName
A DOMString containing the name of the key you want to create/update.

keyValue
A DOMString containing the value you want to give the key you are creating/updating.

This means you will need to save a serialized string representation of your array to localStorage and, likewise, deserialize an array when you retrieve. Luckily, JavaScript has some built in utils to do this for you by using [JSON.parse][3] and [JSON.stringify][3].

Something like this:

var title = prompt("What would you like your title to be?");
var titles = JSON.parse(localStorage.getItem('titles') || '[]');
if(titles.indexOf(title) < 0) {
  titles.push(title);
}
localStorage.setItem("titles", JSON.stringify(titles));
rgthree
  • 7,217
  • 17
  • 21