My code is below. I’m using isNaN()
but the problem is it’s still valid
function numberSearch(str) {
let sum = 0
let strCount = 0
if (str === "") {
return 0
};
for (let i = 0; i < str.length; i++) {
if (isNaN(Number(str[i]))) {
strCount = strCount + 1 // if it's true, +1
}
sum = sum + Number(str[i]) // if it's a number
}
return Math.round(sum / strCount);
}
//debugger;
let output = numberSearch('Hello6 ');
console.log(output); // --> 1
output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1
How can I count the number and calculate it?
When I using debugger sum is NaN
.. I cant understand well.
The issue is that
sum = sum + Number(str[i])
is being executed even ifisNaN(Number(str[i])) === true
because it is outside of theif
block. You need to wrap it inside of theelse
block so that it only executes if the previous condition is false.Think of the following case
I suggest you add one more
if-else
for each case. If it doesn’t fall into the above case.Your main issue is that you add a number anyway. In the line
sum = sum + Number(str[i])
is read for each and every character. So even the last char will beNaN
and it would be added to the sum, making itNaN
.I’m not quite sure what you’re trying to do here, it seems like you are trying to get the sum and divide it by the number of non number characters.
You need to skip those in the sum. There are plenty of ways to do it, and some other problems with the code, but to keep the changes to your code to a minimum I say, just do this:
I would probably do it slightly different than in the original code, and find out how many numbers there are, and work from there
For the original code however, you should just add a
continue
in your if branch and your code will work (as long as not all characters are numbers, cause then you would divide by 0 and you didn’t specify how to handle such a case)Just remember to verify to not divde by 0 if all are numbers 🙂