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 增强版的更多相关文章
- 将表里的数据批量生成INSERT语句的存储过程 增强版
将表里的数据批量生成INSERT语句的存储过程 增强版 有时候,我们需要将某个表里的数据全部或者根据查询条件导出来,迁移到另一个相同结构的库中 目前SQL Server里面是没有相关的工具根据查询条件 ...
- 最新GHOST XP系统下载旗舰增强版 V2016年
系统来自:系统妈:http://www.xitongma.com 深度技术GHOST xp系统旗舰增强版 V2016年3月 系统概述 深度技术ghost xp系统旗舰增强版集合微软JAVA虚拟机IE插 ...
- 最新深度技术GHOST XP系统旗舰增强版 V2016年
来自系统妈:http://www.xitongma.com 深度技术GHOST xp系统旗舰增强版 V2016年 系统概述 深度技术ghost xp系统旗舰增强版集合微软JAVA虚拟机IE插件,增强浏 ...
- WinNTSetup v3.8.7 正式版绿色增强版
最强系统安装利器:WinNTSetup 现已更新至 v3.8.7 正式版!这次更新修复调整了诸多问题,新版非常好用接近完美!WinNTSetup 现在已经自带BCDBoot 选项,并且完全支持Wind ...
- HTML5 的web储存: localStorage & sessionStorage
早期的浏览器使用cookie储存,HTML5新增web储存,包括:localStorage 和 sessiongStorage; localStorage:可以永久储存: sessionStorage ...
- iOS开发和localStorage/sessionStorage
一.前言 在近期的工作中,有前端同学告诉我要清除localStorage,我当时对localStorage完全没有概念,所以就在w3c看了一下相关的内容,下面简单的介绍一下.算是对iOS开发者普及H5 ...
- 将表里的数据批量生成INSERT语句的存储过程 继续增强版
文章继续 桦仔兄的文章 将表里的数据批量生成INSERT语句的存储过程 增强版 继续增强... 本来打算将该内容回复于桦仔兄的文章的下面的,但是不知为何博客园就是不让提交!.... 所以在这里贴出来吧 ...
- cookie, localStorage, sessionStorage区别
cookie 有过期时间,默认是关闭浏览器后失效,4K,兼容ie6,不可跨域,子域名会继承父域名的cookielocalStorage 永不过期,除非手动删除,5M,兼容IE8,不可跨域,子域名不能继 ...
- CentOS6.5安装Tab增强版:bash-completion
CentOS6.5安装Tab增强版:bash-completion,可补全命令参数: 因为CentOS官方源并不带有bash-completion的包,所以,为了可用yum安装,增加epel的源, 首 ...
随机推荐
- 免费报名 | 腾讯云自研数据库CynosDB交流会
本文由云+社区发表 作者:技术沙龙 All in 云+时代,数据库的高可用性.按需付费.按需扩展等属性解放了大批开发者.腾讯发布的自研数据库CynosDB作为国内首款同时兼容MySQL和PG的云原生数 ...
- Maven教程(4)--Maven管理Oracle驱动包
由于Oracle授权问题,Maven3不提供Oracle JDBC driver,为了在Maven项目中应用Oracle JDBC driver,必须手动添加到本地仓库. 手动添加到本地仓库需要本地有 ...
- 前端异步技术之Promise
前言 从事前端的朋友或多或少的接触过Promise,当代码中回调函数层级过多你就会发现Promise异步编程的魅力,相信此文一定能帮你排忧解惑! Promise概念 Promise是JS异步编程中的重 ...
- Flask入门之完整项目搭建
一.创建虚拟环境 1,新建虚拟环境 cmd中输入:mkvirtualenv 环境名 2,在虚拟环境安装项目运行所需要的基本模块 pip install flask==0.12.4 pip instal ...
- [转]Nodejs进程间通信
本文转自:http://www.cnblogs.com/rubyxie/articles/8949417.html 一.场景 Node运行在单线程下,但这并不意味着无法利用多核/多机下多进程的优势 事 ...
- Docker搭建MongoDB
1. Docker搭建Mongodb 1.1 获取docker镜像 docker pull mongo 1.2 创建mongodb容器 docker run --name my-mongo -p 27 ...
- hive 中遇到的正则
1.提取科室中,"科"字前面的内容 regexp_extract(t1.doctor_department_format,'(.*)科') 2.去除字符串中的数字 第一种方式: S ...
- Python全栈开发之---redis数据库
1.redis简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(s ...
- cookie特殊字符在游览器被转义
环境:vue2.x axios 1.如果只是前端自己用,那么可以用 encodeURIComponent(string) 存 ,用decodeURIComponent(string)取. 2.遇到一种 ...
- #WEB安全基础 : HTML/CSS | 0x10.1更多表单
来认识更多的表单吧,增加知识面 我只创建了一个index.html帮助你认识它们 以下是代码 <!DOCTYPE html> <html> <head> <m ...