我有一个JSON对象,它可以存储一个Date(和/或任何其他JS对象),但是我不知道如果它存在,它将如何解决它。例如,我有这个示例代码,但它不起作用:
for(var key in value){
if(value.hasOwnProperty(key)){
if(typeof value[key] == 'object'){
if(value[key].Date){
console.log('this is a date')
}
else{
console.log('not a date');
}
}
}
}
然而,它只是保持返回not a date
。如果我使用Firebug或WebKit中的开发者控制台检查JSON对象,我会在相应的JSON项目中看到__proto__: Date
...那么,我该如何获取它或检查它?
- 编辑 -
以下是我在调试器中看到的内容:
Object
->isADate: Fri Nov 26 2010 20:30:57 GMT-0800 (Pacific Standard Time)
--->__proto__: Date
->notADate: "some string"
--->__proto__: Object
这是JSON即时创建:
var dateStorage = new storageLocker('date-test');
dateStorage.save({'isADate':new Date(),'notADate':'some string'});
以下是我脚本的这部分代码(http://github.com/oscargodson/storagelocker)
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];
console.log(value[key].Date);
if(typeof value[key] == 'object'){
if(value[key].Date){
console.log('this is a date')
}
else{
console.log('not a date');
}
}
}
}
localStorage.setItem(this.catalog,JSON.stringify(json));
return this;
}
非常感谢!希望这会有所帮助!
答案 0 :(得分:2)
您想看一下:How to know if an object is a date or not with JavaScript
基本上“最安全” - 不是100%故障保险,但你应该没问题 - 是做功能检测。
但是,请确保您的JSON条目确实是日期对象而不是字符串,在这种情况下,这不起作用,您需要使用new Date()
或Date.parse()
来制作它是一个约会对象。
编辑:发表您的2条评论:
JSON不允许您以Date格式存储对象。所以,这里已经存在差异。要么你没有真正处理JSON对象,要么你没有应对它们。
有关如何使用JSON.parse的reviver参数的信息,请参阅此页面以获取有关使用JSON in JavaScript的官方文档,因为日期应存储为字符串,然后“复活”到Date对象。
此外,typeof返回对象并不一定意味着您不处理字符串,例如:
typeof new String("test") // object
现在假设您此时确实有一个Date对象,我看不出对value[key].Date
的测试是如何工作的。在你的调试控制台中尝试一下,因为你有FireBug:
var t = new Date();
alert(t.Date) // undefined
alert(t.getMonth) // code of the function, so not undefined
alert(typeof t.getMonth != 'undefined') // true
因此,对getMonth
,getDay
和其他人使用测试组合可以解决问题。
答案 1 :(得分:0)
如果像我一样,你在这里寻找一种方法来发现JSon日期值等于的日期/时间,你可以这样做(使用wscript - Windows脚本宿主):
将以下文本保存到名为test.js的文件中(用您自己的日期值替换1396566000000)
var date = new Date(1396566000000); WScript.Echo(日期);
从命令提示符运行:
wscript test.js