让localStorage存取JSON更高效
要把一个obj对象存进localStorage,大致步骤是:obj => objStr=JSON.stringify(obj) => localStorage.setItem(name, objStr);
要把一个localStorage取出转成obj对象,大致步骤是:objStr=localSotrage.getItem(name) => obj = JSON.parse(objStr);
现在看来好像没什么问题,如果要修改localStorage中保存的obj的某个属性时,那就要先取出,修改,再存进;这样一来要写大量的JSON转换和localStorage存取代码,而且还有承担存取name写错的风险。那要解决这个问题,就把自带方法封装一下
var wrapJsonStorage = function(name) { var ls = localStorage, lo = ls.getItem(name) || '{}'; try { lo = JSON.parse(lo); //判断lo是否是对象 lo = Object(lo) === lo ? lo : {}; } catch(e) { lo = {}; } return { has: function(attr) { return !!lo[attr]; }, get: function(attr) { return lo[attr]; }, set: function(attr, val) { lo[attr] = val; return this; }, remove: function(attr) { delete lo[attr]; return this; }, clear: function() { lo = {}; return this; }, save: function() { //lo为空时则删除localStorage if(this.size() > 0) { ls.setItem(name, JSON.stringify(lo)); } else { ls.removeItem(name); } return this; }, size: function() { return Object.keys(lo).length; }, toJSON: function() { var o = {}, i; for(i in lo) { o[i] = lo[i]; } return o; }, toString: function() { return JSON.stringify(lo); } }; };
使用方法:
注:使用set,remove,clear方法后有调用save方法才会同步到localStorage,主要为了减少io次数,增加效率