最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the last stored localStorage item - Stack Overflow

programmeradmin0浏览0评论

Say we have:

localStorage.setItem("key1", "value1");
localStorage.setItem("key2", "value2");
localStorage.setItem("key3", "value3");
localStorage.setItem("key4", "value4");
localStorage.setItem("key5", "value5"); // the last one

Is there a way to get the last stored item, without a knowledge of its key? So, we don't know if its key is key5 or key10 or fbjfbjfkbjkf. We just want to get this item.

Something like?

localStorage.getLastStoredItem();

Say we have:

localStorage.setItem("key1", "value1");
localStorage.setItem("key2", "value2");
localStorage.setItem("key3", "value3");
localStorage.setItem("key4", "value4");
localStorage.setItem("key5", "value5"); // the last one

Is there a way to get the last stored item, without a knowledge of its key? So, we don't know if its key is key5 or key10 or fbjfbjfkbjkf. We just want to get this item.

Something like?

localStorage.getLastStoredItem();
Share Improve this question edited Oct 15, 2016 at 21:02 nem035 35.5k6 gold badges92 silver badges104 bronze badges asked Jan 18, 2016 at 4:23 john c. j.john c. j. 1,1955 gold badges37 silver badges92 bronze badges 6
  • Does StorageEvent do what you want? – moof2k Commented Jan 18, 2016 at 4:26
  • 2 No, if you want a timeline of your write operations you'll have to create it yourself. What is your actual use case? – Bergi Commented Jan 18, 2016 at 4:29
  • 1 I think this is impossible, without remembering the last key yourself. The order of localStorage.keys is not guaranteed; Chrome seems to return the keys in alphabetical order. – user663031 Commented Jan 18, 2016 at 4:30
  • proof for torazaburos point: jsfiddle/taqcsz5m – Stefan Dochow Commented Jan 18, 2016 at 4:34
  • 1 IE returns the values in the order they have been set in. In Firefox the order of the returned keys does not appear to make any sense at all. – Stefan Dochow Commented Jan 18, 2016 at 4:37
 |  Show 1 more ment

1 Answer 1

Reset to default 4

localStorage has no exact concept (it is implementation-defined) of the order of items stored, it should be used as a key-value store.

The simplest solution for you would be to somehow store the last key entered. For example, you can create a wrapper function that stores your items, and updates the last key:

var lastKey; // somewhere in your code, in the outer scope of `add()` and `getLast()`

// ...

function add(key, value) {
    lastKey = key;                    
    localStorage.setItem(key, value);
}

function getLast() {
    return localStorage.getItem(lastKey);
}

Here's a sample Fiddle

Maybe you can make an object for your storage purposes that will keep track of all of this. You can also encapsulate the lastKey as a private variable through a closure so you can't accidentally change it:

var MyStorage = {};
(function(s) {
    var lastKey;
    s.add = function(key, value) { /* ... */ };
    s.getLast = function() { /* ... */ }
})(MyStorage);

Now only MyStorage.add() and MyStorage.getLast() can access the lastKey. Also, if you use a wrapper object like MyStorage, you can for example change your store to sessionStorage internally without affecting any code using MyStorage


EDIT

As suggested in the ments by user2181397 and nnnnnn, if you want to persist the value of lastKey through application restarting, you can also store it in localStorage (or sessionStorage depending on your app logic):

var lastKey = localStorage.getItem('lastKey');

Or in the object:

var MyStorage = {};
(function(s) {
    var lastKey = localStorage.getItem('lastKey');
    s.add = function(key, value) { /* ... */ };
    s.getLast = function() { /* ... */ }
})(MyStorage);

EDIT2:

Something like? localStorage.getLastStoredItem;

Another way could be to add the above method directly to localStorage by overriding the Storage.prototype methods instead of creating the MyStorage object:

(function(s) {
    var lastKey = localStorage.getItem('lastKey');

    var _setItem = Storage.prototype.setItem;          // remember the original setItem
    Storage.prototype.setItem = function(key, value) { // define the new setItem
        if (this === window.localStorage) {            // make sure we are calling localStorage's methods
            lastKey = key;                             // remember the last key
        } 
        _setItem.apply(this, arguments);               // call the original setItem
    }

    Storage.prototype.getLast = function() {           // create the necessary custom method to get the last item stored
        if (this === window.localStorage) {            // make sure we are calling localStorage's methods
            return this.getItem.call(this, lastKey);
        }
    }
})();

Usage:

localStorage.setItem('key1', 'val1');
console.log(localStorage.getLast()); // logs 'val1'

Here's a sample Fiddle

NOTE: Since we are editing Storage.prototype, extending this functionality to other Storage API methods is just a matter of removing the if (this === localStorage) or adding another condition to it.

发布评论

评论列表(0)

  1. 暂无评论