gpt4 book ai didi

javascript - 检查我的脚本中的对象类型?

转载 作者:行者123 更新时间:2023-12-02 20:30:15 25 4
gpt4 key购买 nike

我正在编写一个 localStorage 包装器,以便在需要执行更强大的查询时更轻松地插入和检索数据。

我的脚本在这里: https://github.com/OscarGodson/storageLocker

我的脚本的用户问我如何保存日期,我告诉他正确的过程(将 new Date().getTime() 保存到 JSON 并使用类似 new Date(json.time) 但他试图执行 hisStorage.save({'the_date':new Date()}),但令他惊讶的是,当他去获取格式错误的数据。

所以,我的问题是,如何捕获像这样的插入和其他对象(也许是事件?),将它们转换为用户存储在 JSON 中并正确检索?我一整天都在研究它,但我不知道如何检查某些类型的对象并通过某些 switch case 进行相应的转换。

我的脚本的保存和检索部分如下所示:

保存数据:

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;
}
};

最佳答案

使用 instanceof 运算符检查属性是否是 Date 的实例:

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

问题是;在 getter 中,你如何知道哪些值需要再次恢复?您必须依赖某种字符串格式,并接受这样的事实:如果用户以这种格式保存字符串,那么它将被恢复为日期。

关于javascript - 检查我的脚本中的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4294258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com