尝试添加一个数组,但结果返回NaN [英] Trying to add up an array, but result returns NaN

查看:133
本文介绍了尝试添加一个数组,但结果返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个名为hoursString的字符串,看起来像

  4.3 | 2.4 | 3.4 | 3.0 | 2.64 | 3.0 | 1.0 | 0.0 | 2.6 | 3.4 | 

我将字符串拆分为一个数组,我试图做的是将所有数字加起来将其返回到divtest中的html页面。



JAVASCRIPT:

  var hours = hoursString.split(| ); 

var total = 0;
for(var i = 0; i {
total + = hours [i];
}
document.getElementById(test)。innerHTML = total;

结果是NaN。有人能告诉我我做错了什么吗?
Thanks!

解决方案

4.3 | 2.4 | 3.4 | 3.0 | 2.64 | 3.0 | 1.0 | 0.0 | 2.6 | 3.4 |

删除最后一个|,split会在数组的末尾添加一个空字符串, NaN和NaN +的数值计算结果为NaN b
$ b 编辑:是的,parseFloat也是必须的,否则结果将是一个字符串而不是NaN


So I have a string called hoursString that looks like

4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|

I split the string into an array and what I am trying to do is add up all the numbers and return it to the html page in the div "test".

JAVASCRIPT:

var hours=hoursString.split("|");

    var total=0;
    for (var i=0;i<hours.length;i++)
        {
        total += hours[i];
        }
    document.getElementById("test").innerHTML=total;

The result is NaN. Can someone tell me what I am doing wrong? Thanks!

解决方案

4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|

remove the last |, split will otherwise add an empty string at the end of the array which will give NaN and NaN + number evaluates to NaN

edit: and yes, parseFloat is necessary too, otherwise the result will be a string instead of NaN

这篇关于尝试添加一个数组,但结果返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆