2010-11-27 88 views
0

我正在編寫一個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; 
    } 
}; 
+0

http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in​​-javascript – Stephen 2010-11-27 22:38:44

回答

2

使用instanceof操作者檢查該物業是否爲Date的實例:

if (value[key] instanceof Date) { 
    //serialize in some way 
    ... 
}else{ 
    json[key] = value[key]; 
} 

問題是;在吸氣機中,你怎麼知道哪些值需要再次恢復?你必須依賴一些字符串格式,並接受如果用戶以這種格式保存一個字符串,那麼它將作爲一個日期復活。

+0

是的,這也是事實。我正在考慮一些自定義日期存儲(如localStorage)sLDate(123467890)`或其他東西。如果您有其他建議,請告訴我。非常感謝,我會嘗試一下。以前的人試圖幫助我說這是不可能的,因爲你不能在JSON中存儲對象...所以我想我會再問:) – 2010-11-27 22:57:38