Trying to add up an array, but result returns NaN

雨燕双飞 提交于 2019-12-25 07:35:42

问题


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!


回答1:


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




回答2:


var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|",
    hours = hoursString.split("|"),
    total = 0;
for (var i = 0; i < hours.length; i++) {
    total += parseFloat(hours[i]) || 0; // see explanation
}
document.getElementById("test").innerHTML = total;

Why the || 0? Because it checks if the string is "", if so the || operand will return the second value, in this case 0.

This will output 25.740000000000002. See this answer on the cause of the "wrong" result, and here is a working fiddle.




回答3:


Your issue is that each element in hours is still a string value even though it is written as a number. The easiest way to fix this would be to use javascripts parseFloat() function.

Example:

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

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

EDIT: Changed from parseInt to parseFloat




回答4:


var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|"
var hours=hoursString.split("|");

var total=0;
var idx = 0;
for(idx in hours) {
    total += +hours[idx];
}

alert(total);

FIDDLE



来源:https://stackoverflow.com/questions/17053263/trying-to-add-up-an-array-but-result-returns-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!