简体   繁体   English

Javascript parseFloat()有时会返回NaN - 可能只是在旧版本的Firefox上

[英]Javascript parseFloat() sometimes returns NaN - Possibly just on older versions of Firefox

I have tested this application on all current major browsers and it works reliably and correctly. 我已经在所有当前主流浏览器上测试了这个应用程序,它可靠且正确地工作。 The app is now deployed and I am getting reports that sometimes the result is NaN. 该应用程序现已部署,我收到报告,有时结果是NaN。

The function below uses parsefloat() to find the total of a column of prices in a table. 下面的函数使用parsefloat()来查找表中一列价格的总和。 Sometimes that total is displayed as NaN. 有时总计显示为NaN。 I have been unable to reproduce it and the customers who report the issue thus far have not been sufficiently technically competent to tell me what browser they are using. 我一直无法重现它,到目前为止报告问题的客户在技术上没有足够的能力告诉我他们正在使用什么浏览器。 One person sent a screen shot of Firefox on a Mac and another knew it was Firefox on Windows. 一个人在Mac上发送了Firefox的屏幕截图,另一个人知道它是Windows上的Firefox。

In the below code, this line: 在下面的代码中,这一行:

var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);

properly sets linePrice to 6.50 and the value of innerHTML is "$6.50". 将linePrice正确设置为6.50,innerHTML的值为“$ 6.50”。 The next line calls parseFloat(linePrice); 下一行调用parseFloat(linePrice);

Finally, this line: 最后,这一行:

document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });

Causes NaN to be displayed instead of the column total. 导致显示NaN而不是列总数。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Here is the code: 这是代码:

  function totalTbl()
  {
    var table = document.getElementById('myTbl');
    var rows = table.getElementsByTagName('tr');

    var tableTotal = 0;

    // Skip the first (header) row and the last (add row) row
    len = rows.length - 2;
    numRows = len - 1;

    for (var i = 1; i < len; i++)
    {
      var cell = rows[i].cells[5];
      if (cell.firstChild != null)
      {
        var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);

        tableTotal += parseFloat(linePrice);
      }
    }

    document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });

  }

I feel it'll be difficult to find one point in your code where this is being caused without more code to examine, so I'll attempt to address a few issues and hopefully we'll hit on the issue. 我觉得在你的代码中找到一个没有更多代码要检查的问题是很困难的,所以我会尝试解决一些问题,希望我们能够解决这个问题。

So firstly, never use != or == , this performs type coercion, the rules of which are unintuitive and unmemorable and are best simply avoided. 所以首先,永远不要使用!=== ,这会执行类型强制,其规则是不直观和不可取的,最好简单地避免。 Instead always use === or !== , which will not perform type coercion. 而是始终使用===!== ,它不会执行类型强制。 If do want to perform type coercion I would do so explicitly. 如果想要执行类型强制,我会明确地这样做。

Secondly, if these values are being provided by user input I'd argue against using a naive solution such as .substr , and in its place use a regex such as /\\d+(.\\d*)?/ . 其次,如果这些值是由用户输入提供的,我反对使用诸如.substr类的天真解决方案,并且在其位置使用正则表达式,例如/\\d+(.\\d*)?/ If it's not from user input you're probably safe. 如果它不是来自用户输入,那么你可能是安全的。

Thirdly, and what I most suspect is the issue, is toLocaleString . 第三,我最怀疑的是问题,就是对toLocaleString It was my understanding that toLocaleString was fairly untrustworthy as a function due to the different implementations provided by different browsers. 据我所知,由于不同浏览器提供的不同实现, toLocaleString作为一个函数是相当不值得信任的。 I'm on a Mac, and Chrome produces $7.50 , and Firefox produces US$7.50 . 我在Mac上,Chrome产生$7.50 ,Firefox产生US$7.50 These seem fine as they are, but hint at possible issues for older versions of these browsers, and also if you were to attempt naive string manipulation on them you'd quickly encounter problems. 这些似乎很好,但暗示这些浏览器的旧版本可能存在问题,而且如果您尝试对它们进行天真的字符串操作,您很快就会遇到问题。 It's fairly easy to replace toLocaleString with a safe and concise solution. 使用安全简洁的解决方案替换toLocaleString相当容易。

document.getElementById('totalPrice').innerHTML = '$' + tableTotal.toFixed(2)

This assumes typeof tableTotal === 'number' , otherwise you must simply do (+tableTotal).toFixed(2) to perform type coercion. 这假设typeof tableTotal === 'number' ,否则你必须简单地执行(+tableTotal).toFixed(2)来执行类型强制。

Good luck, and let me know if I've solved your problem. 祝你好运,如果我已经解决了你的问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM