Localstorage listing

I made my own function using this:

function save(title, url)
{
 for (var i = 1; i < localStorage.length; i++) 
 {
  localStorage["saved-title_" + i + ""] = title;
  localStorage["saved-url_" + i + ""] = url;
 } 
}

function listFavs()
{
 for (var i = 1; i < localStorage.length; i++) {
    console.log(localStorage["saved-fav-title_" + i + ""]);
 }
}

      

save () happens when someone clicks on this:

onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';

      

However ... it doesn't show the localStorages saved, how should I get it to work?

+2


a source to share


1 answer


Perhaps this is because you are using a key 'saved-title_' + i

to store the value and 'saved-fav-title_' + i

to retrieve it?

The difference lies in the fav - part .

And your localStorage list should throw errors, since there is no guarantee that all the elements in it have a key that matches the pattern 'saved-fav-title_' + i

- in fact, this is not guaranteed in the way that you yourself enter keyed elements in the form 'saved-url_'+ i

.



So, if you want to list the elements correctly with a key matching the pattern, use

function listFavs(){
    var key;
    for (var i = 0, len = localStorage.length; i < len; i++){
        key = localStorage.key(i);
        if ((/^saved-fav-title_/).test(key)) {
            console.log(localStorage.getItem(key);
        }
   }
}

      

+4


a source







All Articles