简体   繁体   中英

Why is'NaN' in JavaScript and how do I fix it?

I have created a program that tells you a program that takes a number in JavaScript and tells you the various properties of that number.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
        <script>
            
            var div_sum = 0
            var num = Number(prompt('Please enter the number'))
            var pn_result = true
            for(var i = 2; i < num; i++){
                if(num % i === 0){
                    var pn_result = false
                    break
                }
            }
            if(pn_result){
                alert(String(num) + 'is a prime')
            } else {
                alert(String(num) + 'is not a prime\n' + String(num) + '=' + String(i) + 'x' + String(num / i))
            }
            var div_list = []
            for(var div = 1; div < num + 1; div++){
                if(num % div === 0){
                    div_list.push(div)
                }
            }
            var div_len = div_list.length
            alert('Number of divisor is' + String(div_len) )
            
            for(var i = 0; i < div_len + 1; i++){
                var div_sum = div_sum + div_list[i]
            }
            var div_sum = div_sum - num
            alert(div_sum)
        </script>
    </body>
</html>

At the end, I was curious if that number was a perfect number, so I output the sum of the divisor excluding myself.

But the execution result came out as'NaN'.

Oddly enough, the other operations did so in a finished state. What is'NaN' and how do I fix it?

The main issue is this line. You are iterating 1 more time than the length of div_list .

for(var i = 0; i < div_len + 1; i++){
  var div_sum = div_sum + div_list[i]
}

It should be

for(var i = 0; i < div_len; i++){
  var div_sum = div_sum + div_list[i]
}

Other issues include declaring redeclaring div_sum inside the for loop , and again immediately outside. You should declare it only once, and then reassign new values to it as such.

var div_sum = 0;
for(var i = 0; i < div_len + 1; i++){
  div_sum = div_sum + div_list[i]
}
div_sum = div_sum - num;

And finally, you should also use camelCase to name JavaScript variables. That is the normal convention. Instead, you are using the snake_case convention, which is not usually used in JavaScript land.

change this

for(var i = 0; i < div_len + 1; i++)
  {
    var div_sum = div_sum + div_list[i]
  }

to this and it will work

for(var i = 0; i < div_len; i++)
   {
     var div_sum = div_sum + div_list[i]
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM