Trying to add up an array, but result returns NaN

2019-09-03 14:45发布

问题:

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