var storage=(function(opts) { ‘use strict‘; function StorageHandle(storage) { this.storage = window[storage] || window.sessionStorage; } StorageHandle.prototype = { constructor: StorageHandle, //存入session的方法 setItem: function(key, param) { if (typeof param == ‘object‘) { this._setStorages(key, param); } else { this._setStorage(key, param); } }, _setStorage: function(key, val) { this.storage.setItem(key, val); }, _setStorages(key, obj) { var l = JSON.stringify(obj); this.storage.setItem(key, l); }, //获取数据,传入获取的name getItem: function(key) { var data = this.storage.getItem(key); if(!!data){ console.warn(‘当前session中没有‘+key+‘这个参数‘); } return JSON.parse(data); }, //一次获取多个key getItems: function(obj) { if (typeof obj !== ‘object‘) { console.error(‘此方法需要一个对象‘); return false; } var objType = Object.prototype.toString.call(obj); //结果用一个对象来表示 var res = {}; if (objType === ‘[object Array]‘) { for (var i of obj) { let val = this.getItem(i); res[i] = val; } } else if (objType === ‘[object Object]‘) { for (var i in obj) { if (obj.hasOwnProperty(i)) { res[i] = this.getItem(obj[i]); } } } return res; } } return new StorageHandle(opts); });
调用方法有以下几种
var f=storage();
f.setItem(‘123‘,[1,34,5,6,‘fasd‘])
f.setItem(‘123‘,‘12314234‘);
f.setItem(45,6546456)
console.log(f.getItems([‘123‘,45]))
console.log(f.getItems({a:‘123‘,b:45}))
console.log(f.getItem(‘123‘));
默认是sessionStorage。如果要用localStorage。
在storage方法中传入一个localStorage参数即可
var f=storage(‘localStorage‘);
用了for of 遍历数组和let ,可能兼容不好。有报错改成普通for循环和var
时间: 2024-09-30 06:37:03