HTML5 local storage sort

后端 未结 2 1189
北恋
北恋 2020-12-20 22:22

I am using local storage to store user entries and am displaying the entries on another page. I need a way to sort them based on the most recent date and time of edit. Is th

相关标签:
2条回答
  • 2020-12-20 23:10

    If your keys/values have an inherent order to them (alphabetical, numerical, etc), then putting a timestamp in them may be superfluous. Although the Storage object has no sort method, you can create a new Array() and then sort that.

    function SortLocalStorage(){
       if(localStorage.length > 0){
          var localStorageArray = new Array();
          for (i=0;i<localStorage.length;i++){
              localStorageArray[i] = localStorage.key(i)+localStorage.getItem(localStorage.key(i));
          }
       }
       var sortedArray = localStorageArray.sort();
       return sortedArray;
    }
    

    The disadvantage to this is that the array is not associative, but that is by nature of the JavaScript Array object. The above function solves this by embedding the key name into the value. This way its still in there, and the functions you'd use to display the sorted array can do the footwork of separating the keys from the values.

    0 讨论(0)
  • 2020-12-20 23:12

    You've got to pair the timestamp with the stored value somehow, you can create a wrapper object for each value and store the value and the timestamp in a single object. Assuming you have a value myvalue you want to store with reference myref:

    var d=new Date();
    var storageObject = {};
    storageObject.value = myvalue;
    storageObject.timestamp = d.getTime();
    localStorage.setItem(myref, JSON.stringify(storageObject));
    

    On the other page you then need to rehydrate your objects into an array and implement your compareFunction function.

    Your other option would be to use Web SQL Database and Indexed Database API which lets you more naturally store and query this sort of multifaceted info, but you would probably have to create some sort of abstract wrapper to make things work easily cross browser.

    0 讨论(0)
提交回复
热议问题