简体   繁体   中英

HTML5 localstorage difficulty

What I was trying to do is to store in structure below inside localstorage

localstorage -> hash1 -> {name11, name12, name13, ...} 
             -> hash2 -> {name21, name22, name23, ...} 
              ...

I'm collecting names to an array then pushing like below

files.push(file.name);
localStorage.setItem(hash, JSON.stringify(files));

I thought that localstorage will be like an empty array and when I loop through localstorage I will get only my hashes. But now when I loop like below

for(var hash in window.localStorage){
    var files = JSON.parse(localStorage.getItem(hash));
    var filesHtml= [];
    $.each(files, function(i, item) {
        filesHtml.push('<li><a href="/' + hash+'/'+item + '">' + item + '</a></li>');
    });
   ...

}

I'm getting bunch of other data in localstorage. How can I collect my hashes like below

localstorage ->history -> hash1 -> {name11, name12, name13, ...} 
                       -> hash2 -> {name21, name22, name23, ...} 
                        ...

and create three dimensional history array inside localstorage so that when I loop through history I will get only my hashes, no other data? Any solution?

How about using arrays ?

$(document).ready(function(){
    var hashes = [];
    hashes[0] = ["name1", "name2", "name3"];

    localStorage["hashes"] = JSON.stringify(hashes);


    var restoredHashes = JSON.parse(localStorage["hashes"]); 

    for(var i = 0; i < restoredHashes.length; i++){

        var names = restoredHashes[i];

        for(var j = 0; j < names.length; j++)
        {
            $("#output").append(names[j]  + "<BR/>");
        }
    }

});

Edit: Redid code to actually work. Check JSFiddle

Edit: Added code to JSFiddle example to prove that "hashes" is persisted in localStorage. Check JSFiddle version2

I think this will help you

for(var hash in window.localStorage){
    if(window.localStorage.hasOwnProperty(hash)){
         //Do your work
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM