闭包-缓存数据

var searchBox = (function() {
    var cache = {},count = 0, index = [];
    return function(key, value) {
        if (cache[key]) {
            return value;
        }
        cache[key] = value;
        count += 1;
        index.push(key)
        if (count > 2) {
            index.shift() //如果超出了限制,将最早的key删除
        }
        return cache;
    }
})();
console.log(searchBox("name", "xxax")) // {name: "xxax"}
console.log(searchBox("name", "xxax")) // xxax
console.log(searchBox("name", "xxax")) // xxax
console.log(searchBox("age", 23)) // {name: "xxax", age:23}
console.log(searchBox("age", 23)) // 23 
posted @ 2019-12-18 16:15  雨夜稻草  阅读(501)  评论(0编辑  收藏  举报