我正在編寫一個localStorage包裝器,以便在需要執行更健壯的查詢時更容易地插入和檢索數據。檢查腳本中對象的類型?
我的腳本是在這裏: https://github.com/OscarGodson/storageLocker
我的腳本的用戶問我,他怎麼能節省時間,我告訴他正確的程序(保存new Date().getTime()
到JSON和東西復活它像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;
}
};
http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript – Stephen 2010-11-27 22:38:44