代码之家  ›  专栏  ›  技术社区  ›  Oscar Godson

检查脚本中的对象类型?

  •  0
  • Oscar Godson  · 技术社区  · 13 年前

    我正在编写一个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;
        }
    };
    
    1 回复  |  直到 13 年前
        1
  •  2
  •   Sean Kinsey    13 年前

    使用 instanceof 运算符检查属性是否为 Date :

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

    问题是,在getter中,你如何知道哪些价值观需要再次复活?您将不得不依赖一些字符串格式,并接受如果用户以这种格式保存字符串,那么它将作为日期恢复。