我正在编写一个localStorage包装器,以便在需要进行更健壮的查询时更容易插入和检索数据。
我的剧本在这里:
https://github.com/OscarGodson/storageLocker
我脚本的一个用户问我如何保存日期,我告诉他正确的过程(保存
new Date().getTime()
使用类似于
new Date(json.time)
但他想这么做
hisStorage.save({'the_date':new Date()})
,但令他惊讶的是,当他去获取数据时,它的格式是错误的。
所以,我的问题是,如何捕捉这样的插入和其他对象(可能是事件?),将它们转换为用户存储在JSON中并正确检索?我一整天都在做这个工作,我不知道如何检查某些类型的对象,并通过一些开关盒进行相应的转换。
我的脚本的保存和检索部分如下所示:
保存数据:
storageLocker.prototype.save = function(value){
var json = JSON.parse(localStorage.getItem(this.catalog));
if(json == null){json = {};}
for(var key in value){
if(value.hasOwnProperty(key)){
json[key] = value[key];
}
}
localStorage.setItem(this.catalog,JSON.stringify(json));
return this;
}
获取数据:
storageLocker.prototype.get = function(value){
json = JSON.parse(localStorage.getItem(this.catalog));
if(json == null){json = {};}
if(value){
if(typeof json[value] !== 'undefined'){
return json[value];
}
else{
//Makes it so you can check with myStorage.get('thisWontExist').length
//and it will return 0 and typeof will return object.
return new Object('');
}
}
else{
return json;
}
};