localStorage sessionStorage 增强版

1. 保留了localStorage sessionStorage的(setItem getItem removeItem clear key)api,使用上几乎差不多
2. 增强了setItem方法,增强版的可以设置值为undefined null array object string number类型的值
3. 增加了(has getAll forEach)api

源码如下

/**
* Created by Sorrow.X on 2018/3/30.
* 本地存储实现, 封装localStorage和sessionStorage
*/ ;(function() {
const api = {
setItem(key, val) {
if (tip(arguments, 'setItem', 2)) { return }
this.storage.setItem(key, serialize(val))
return val
}, getItem(key, defaultVal) {
if (tip(arguments, 'getItem', 1)) { return }
// 如果没有该key, 则自动设置到缓存中去, 默认值为null
if (!this.has(key)) {
return this.setItem(key, defaultVal || null)
}
let ret = deserialize(this.storage.getItem(key))
// 如果有该key,但是值为undefined或者null,则使用默认值且设置到缓存去
if (defaultVal && (ret === undefined || ret === null)) {
ret = this.setItem(key, defaultVal)
}
return ret
}, removeItem(key) {
if (tip(arguments, 'removeItem', 1)) { return }
this.storage.removeItem(key)
}, clear() {
this.storage.clear()
}, key(index) {
if (tip(arguments, 'key', 1)) { return }
this.storage.key(index)
}, has(key) {
if (tip(arguments, 'has', 1)) { return }
// 使用原生getItem方法,如果没有该key会返回字符串"null"
return this.storage.getItem(key) !== null
}, getAll() {
let map = Object.create(null)
this.forEach((key, val) => {
map[key] = val
})
return map
}, forEach(callback, ctx) {
for (let i = 0; i < this.storage.length; i++) {
let key = this.storage.key(i)
callback && callback.call(ctx, key, this.getItem(key), i)
}
}
} let local = Object.assign({
storage: window.localStorage
}, api) let session = Object.assign({
storage: window.sessionStorage
}, api) function serialize(val) {
return JSON.stringify(val)
} function deserialize(val) {
try {
return JSON.parse(val)
} catch (e) {
return val === "undefined" ? undefined : val
}
} function tip(args, operation, actualNum) {
if (args.length < actualNum) {
console.error(
`Failed to execute '${operation}' on 'store': ${actualNum} arguments required, but only ${args.length} present.`
)
return true;
} else {
return false;
}
} if (
typeof module !== 'undefined' &&
typeof exports === 'object'
) {
module.exports = { local, session }
} else {
window.local = local
window.session = session
}
})();

使用姿势(和原生对比):

        // 原生
localStorage.setItem('num', 1)
localStorage.setItem('str', 'str')
localStorage.setItem('arr', [1, 2, 3])
localStorage.setItem('obj', {a: 1, b: 2, c: 3})
localStorage.setItem('undefined', undefined)
localStorage.setItem('null', null) console.log(localStorage.getItem('test'), Object.prototype.toString.call(localStorage.getItem('test')))
console.log(localStorage.getItem('num'), Object.prototype.toString.call(localStorage.getItem('num')))
console.log(localStorage.getItem('str'), Object.prototype.toString.call(localStorage.getItem('str')))
console.log(localStorage.getItem('arr'), Object.prototype.toString.call(localStorage.getItem('arr')))
console.log(localStorage.getItem('obj'), Object.prototype.toString.call(localStorage.getItem('obj')))
console.log(localStorage.getItem('undefined'), Object.prototype.toString.call(localStorage.getItem('undefined')))
console.log(localStorage.getItem('null'), Object.prototype.toString.call(localStorage.getItem('null'))) // 增强版
local.setItem('__num__', 1)
local.setItem('__str__', 'str')
local.setItem('__arr__', [1, 2, 3])
local.setItem('__obj__', {a: 1, b: 2, c: 3})
local.setItem('__undefined__', undefined)
local.setItem('__null__', null) console.log(local.getItem('__test__'), Object.prototype.toString.call(local.getItem('__test__')))
console.log(local.getItem('__num__'), Object.prototype.toString.call(local.getItem('__num__')))
console.log(local.getItem('__str__'), Object.prototype.toString.call(local.getItem('__str__')))
console.log(local.getItem('__arr__'), Object.prototype.toString.call(local.getItem('__arr__')))
console.log(local.getItem('__obj__'), Object.prototype.toString.call(local.getItem('__obj__')))
console.log(local.getItem('__undefined__'), Object.prototype.toString.call(local.getItem('__undefined__')))
console.log(local.getItem('__null__'), Object.prototype.toString.call(local.getItem('__null__')))

上图结果截图:

localStorage sessionStorage 增强版

localStorage sessionStorage 增强版

localStorage sessionStorage 增强版

上一篇:C#快捷键和注释


下一篇:localStorage sessionStorage 和cookie等前端存储方式总结