HTML5 local storage sort

后端 未结 2 1190
北恋
北恋 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

    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.

提交回复
热议问题