Reputation: 491
I have written a function showWorthSum() to return the sum of an array. It does but I have also put a condition if an element of an array is a number then it should be calculated only and rest should be skipped but still, it goes inside the if block in case of NaN and makes the whole result NaN. Why ?
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
//var row1= table1.insertRow(rowCount1);
var arr= [];
for(var count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= addWorth();
//returnedArr.push(addWorth());
totalWorth= 0;
var arrCount= returnedArr.length;
for(var count = 0; count < arrCount; count++)
{
if(typeof(parseInt(returnedArr[count])) == 'number')
{
totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]);
//document.write(returnedArr[count]);
}
}
return parseInt(totalWorth);
}
array: {100.200. 'asdadasd', 322, 22}
Button:
<button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
Upvotes: 0
Views: 68
Reputation: 31
Instead of "typeof(parseInt(returnedArr[count])) == 'number'", you can use isFinite(returnedArr[count]).
isFinite('foo')
false
isFinite('10')
true
isFinite(10)
true
isFinite('898.0900')
true
Upvotes: 2
Reputation: 7305
Try this instead isNaN(parseInt(returnedArr[count])) === false
Although NaN
by definition is Not A Number
, typeof NaN
is number
So to check if a variable is a number use isNaN(value) === false
or !isNaN(value)
Examples:
isNaN(5) => false
isNaN("5") => false
isNaN("-5") => false
isNaN(true) => false
isNaN(false) => false
isNaN({}) => true
isNaN(NaN) => true
isNaN("test") => true
isNaN("5test") => true
isNaN("test5") => true
So you could also use !isNaN(returnedArr[count])
to make it shorter
Upvotes: 1