localStorage是h5中很好用的功能,有着比cookie更快速且容量更大的特性,如果频繁的读取和存储数据,而数据有json,有字符串,就会照成大量代码冗余,封装一起就看起来好很多!
var Storage = (function(){
return {
set: function(key, value, expireSeconds){
localStorage[key] = JSON.stringify({
value: value,
expired: expireSeconds===undefined?undefined:Date.now() + 1000*expireSeconds
})
},
get: function(key){
if(localStorage[key] === undefined){
return
}
var o = JSON.parse(localStorage[key])
if(o.expired === undefined || Date.now() < o.expired){
return o.value
}else{
delete localStorage[key]
}
}
}
})()
Storage.set('name', '饥人谷')
Storage.set('age', 2, 30) ; //设置 name 字段存储的值为'饥人谷'
Storage.set('teachers', ['ruoyu', 'fangfang', 'tom'], 60)
Storage.get('name') // ‘饥人谷’
Storage.get('age') // 如果不超过30秒,返回数字类型的2;如果超过30秒,返回 undefined,并且 localStorage 里清除 age 字段
Storage.get('teachers') //如果不超过60秒,返回数组; 如果超过60秒,返