Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

javascript - HTML5 local storage sort

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 there a way to do this with HTML5. If not, what's the easiest/most effective way to do so?

Thanks for the inputs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...