【问题标题】:Jquery - Strange Number to String conversionJquery - 奇怪的数字到字符串的转换
【发布时间】:2011-12-27 04:48:11
【问题描述】:

我遇到了一个奇怪的不需要的 NumberNaN 的转换,不知道在哪里以及为什么。我显然在这里遗漏了一些东西,但我不知道是什么。

欢迎提出任何建议! ;)

这里是javascript代码:

updatedAbsoluteResult = currentlyDisplayedRentability * investment
resultAgainstReferencial = updatedAbsoluteResult - appropriateReferencialRentability * investment

$('#a0').html('currentlyDisplayedRentability: ' + typeof currentlyDisplayedRentability)
$('#a1').html('investment: ' + typeof investment)
$('#a2').html('updatedAbsoluteResult: ' + typeof updatedAbsoluteResult)
$('#a3').html('appropriateReferencialRentability: ' + typeof appropriateReferencialRentability)
$('#a4').html('resultAgainstReferencial: ' + typeof resultAgainstReferencial )
$('#a5').html('resultAgainstReferencial: ' + resultAgainstReferencial )

这是 HTML 输出:

currentlyDisplayedRentability: number
investment: number
updatedAbsoluteResult: number
appropriateReferencialRentability: number
resultAgainstReferencial: number
resultAgainstReferencial: NaN

一切都是数字类型,但是当我想返回最终结果时,我得到“不是数字”的结果。 任何人都知道为什么?

周末愉快!

【问题讨论】:

  • 它可能相关也可能不相关,但您没有告诉我们appropriateReferencialRentabilityinvestment 的定义在哪里?
  • 一些数字示例会有所帮助...
  • 你真的应该在每一行的末尾使用终结符 (;)。

标签: jquery numbers nan html-rendering


【解决方案1】:

数值类型可以返回 NaN 并且仍然是数值类型。检查 updatedAbsoluteResult、适当的ReferencialRentability 和投资的值以查看其中是否有任何意外值。该等式中的某些内容可能出错了。

【讨论】:

    【解决方案2】:

    问题很可能是 resultAgainstReferencial 是NaN。你得到你的结果是因为:

    typeof NaN == "number"
    

    给你看:

    resultAgainstReferencial = NaN;
    alert(typeof resultAgainstReferencial);   // alerts "number"
    

    你甚至可以在这里看到它:http://jsfiddle.net/jfriend00/t3ubg/

    因此,在上游的某个地方,您正在尝试用非数字的事物进行数学运算。您必须查看所有数字输入的值,看看数据哪里出错了。

    【讨论】:

      【解决方案3】:

      javascript 中的NaN 在技术上仍然是number 类型。它通常是由除以 0 引起的。对另一个 NaN 进行任何数学计算也会返回 NaN

      【讨论】:

        【解决方案4】:

        也许具有讽刺意味的是,NaN 本身就是一个Number

        您可能在某处遇到了失败的parseInt() 呼叫,或许多其他可能性。不看相关代码很难猜到。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-16
          • 2012-03-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多