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 增强版的更多相关文章

  1. 将表里的数据批量生成INSERT语句的存储过程 增强版

    将表里的数据批量生成INSERT语句的存储过程 增强版 有时候,我们需要将某个表里的数据全部或者根据查询条件导出来,迁移到另一个相同结构的库中 目前SQL Server里面是没有相关的工具根据查询条件 ...

  2. 最新GHOST XP系统下载旗舰增强版 V2016年

    系统来自:系统妈:http://www.xitongma.com 深度技术GHOST xp系统旗舰增强版 V2016年3月 系统概述 深度技术ghost xp系统旗舰增强版集合微软JAVA虚拟机IE插 ...

  3. 最新深度技术GHOST XP系统旗舰增强版 V2016年

    来自系统妈:http://www.xitongma.com 深度技术GHOST xp系统旗舰增强版 V2016年 系统概述 深度技术ghost xp系统旗舰增强版集合微软JAVA虚拟机IE插件,增强浏 ...

  4. WinNTSetup v3.8.7 正式版绿色增强版

    最强系统安装利器:WinNTSetup 现已更新至 v3.8.7 正式版!这次更新修复调整了诸多问题,新版非常好用接近完美!WinNTSetup 现在已经自带BCDBoot 选项,并且完全支持Wind ...

  5. HTML5 的web储存: localStorage & sessionStorage

    早期的浏览器使用cookie储存,HTML5新增web储存,包括:localStorage 和 sessiongStorage; localStorage:可以永久储存: sessionStorage ...

  6. iOS开发和localStorage/sessionStorage

    一.前言 在近期的工作中,有前端同学告诉我要清除localStorage,我当时对localStorage完全没有概念,所以就在w3c看了一下相关的内容,下面简单的介绍一下.算是对iOS开发者普及H5 ...

  7. 将表里的数据批量生成INSERT语句的存储过程 继续增强版

    文章继续 桦仔兄的文章 将表里的数据批量生成INSERT语句的存储过程 增强版 继续增强... 本来打算将该内容回复于桦仔兄的文章的下面的,但是不知为何博客园就是不让提交!.... 所以在这里贴出来吧 ...

  8. cookie, localStorage, sessionStorage区别

    cookie 有过期时间,默认是关闭浏览器后失效,4K,兼容ie6,不可跨域,子域名会继承父域名的cookielocalStorage 永不过期,除非手动删除,5M,兼容IE8,不可跨域,子域名不能继 ...

  9. CentOS6.5安装Tab增强版:bash-completion

    CentOS6.5安装Tab增强版:bash-completion,可补全命令参数: 因为CentOS官方源并不带有bash-completion的包,所以,为了可用yum安装,增加epel的源, 首 ...

随机推荐

  1. 【c#】RabbitMQ学习文档(三)Publish/Subscribe(发布/订阅)

    (本教程是使用Net客户端,也就是针对微软技术平台的) 在前一个教程中,我们创建了一个工作队列.工作队列背后的假设是每个任务会被交付给一个[工人].在这一部分我们将做一些完全不同的事情--我们将向多个 ...

  2. 4.计算机启动过程的简单介绍 计算机启动流程 计算机BIOS作用 POST 开机自检 计算机启动顺序 分区表 操作系统启动

    计算机的启动

  3. JsonRequestBehavior不存在问题,JsonRequestBehavior属于哪个dll

    1.C#.Net.C++.JScript.VB语法 获取或设置一个值,该值指示是否允许来自客户端的 HTTP GET 请求. 命名空间: System.Web.Mvc程序集: System.Web.M ...

  4. 第35章 秘密(secrets) - Identity Server 4 中文文档(v1.0.0)

    在某些情况下,客户端需要使用身份服务器进行身份验证,例如 在令牌端点请求令牌的机密应用程序(也称为客户端) API在内省端点验证引用令牌 为此,您可以将秘密列表分配给客户端或API资源. 秘密解析和验 ...

  5. 第3章 支持和规范 - Identity Server 4 中文文档(v1.0.0)

    IdentityServer实现以下规范: 3.1 OpenID Connect OpenID Connect Core 1.0 (规范) OpenID Connect Discovery 1.0 ( ...

  6. Asp.net Core 项目中如何使用 MongoDB 数据库

    内容来源 https://blog.csdn.net/qq_26900081/article/details/83272132 一.添加依赖 1.MongoDB.Driver 2.MongoDB.Bs ...

  7. java_List集合及其实现类

    第一章:List集合_List接口介绍 1).特点       1).有序的: 2).可以存储重复元素: 3).可以通过索引访问: List<String> list = new Arra ...

  8. Maven(十五)Maven 聚合

    聚合解决的问题: 解决每个模块之间都要一个一个安装,一键安装各个模块工程 尤其时在配置继承后要先安装子模块在安装父,模块. 配置方式 自己找一个工程作为聚合工程,配置好后在聚合工程上运行Maven i ...

  9. vue 中promise 异步请求数据

    export function getTypes(type) { return listDictItems({ code: type }).then((res) => { if (res.cod ...

  10. angular懒加载

    生成module和routing.module文件 {//路径 path: 'InfectionFillInComponent', loadChildren: './component/his/inf ...