js 对localStorage的封装

let Store = {
    get: function(key) {
        var value = localStorage.getItem(key);
        if (value) {
            try {
                var value_json = JSON.parse(value);
                if (typeof value_json === 'object') {
                    return value_json;
                } else if (typeof value_json === 'number') {
                    return value_json;
                }
            } catch(e) {
                return value;
            }
        } else {
            return false;
        }
    },
    set: function(key, value) {
        localStorage.setItem(key, value);
    },
    remove: function(key) {
        localStorage.removeItem(key);
    },
    clear: function() {
        localStorage.clear();
    }
};


// 批量保存,data是一个字典
Store.setList = function(data) {
    for (var i in data) {
        localStorage.setItem(i, data[i]);
    }
};

// 批量删除,list是一个数组
Store.removeList = function(list) {
    for (var i = 0, len = list.length; i < len; i++) {
        localStorage.removeItem(list[i]);
    }
};

 

资料分享网站

 

可以加我微信进群,有资料送,也可以讨论问题

 

posted @ 2017-12-15 09:59  浮生如梦似离殇  阅读(3012)  评论(0编辑  收藏  举报