【问题标题】:Typeof Error - Returning a NaN even though both is a numberTypeof Error - 返回 NaN,即使两者都是数字
【发布时间】:2014-07-19 19:08:38
【问题描述】:

我试图找出 diffcurrentDate.getTimezoneOffset 之间的区别。 我检查了它们都是数字,但它显示的是 NaN。

这是我的 js 代码:

$(document).ready(function() {

    // Grab the current date
    var currentDate = new Date();

    // Set some date in the future. In this case, it's always Jan 1
    var futureDate = new Date(currentDate.getFullYear() + 0, 8, 4);

    // Calculate the difference in seconds between the future and current date
    var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;


    console.log(typeof parseInt(currentDate.getTimezoneOffset()))
    console.log(typeof diff)
    console.log(parseInt(currentDate.getTimezoneOffset()))
    console.log(diff)
    console.log(diff - parseInt(currentDate.getTimezoneOffset))

});

谁能向我解释为什么会发生这种情况以及如何解决它?

【问题讨论】:

  • 你没有返回一个数字 - 使用 currentDate.getTimezoneOffset() 返回一个整数偏移量
  • @kennebec 对不起,我犯了一个小错误,你能再检查一下吗?
  • @NevinMadhukarK 您的编辑不适用于最后一部分:console.log(diff - parseInt(currentDate.getTimezoneOffset))
  • @chris97ong 天哪……难怪:|我的错。
  • 只是一个旁注:parseInt(currentDate.getTimezoneOffset)NaN, typeof NaN === 'number'

标签: javascript date type-conversion nan


【解决方案1】:

您的语法在这里是错误的:

   console.log(typeof parseInt(currentDate.getTimezoneOffset))

应该是

console.log(typeof parseInt(currentDate.getTimezoneOffset()))
                                                         ^^ missing brackets here

【讨论】:

  • 是的,我忘了添加这些,问题仍然存在,请检查更新的 qn。
  • 您尚未更正代码中的所有错误。使用正确的语法,这可以在我的浏览器中使用
  • 是的,我想我应该多睡一会儿。感谢您指出。错别字...
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2012-09-21
  • 2013-08-19
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
相关资源
最近更新 更多