Jaxom Nutt
Jaxom Nutt

Reputation: 59

Javascript Calculation - NaN message

Would someone be able to help me with this. When i attempt calculations in Javascript they always seem to fail and come back as NaN

function SpinRand()
{

    var a,b,c,d,e,f;

    a=Math.floor(Math.random()*9);

    b=Math.floor(Math.random()*9);

    c=Math.floor(Math.random()*9);

    d=Math.floor(Math.random()*9);

    e=Math.floor(Math.random()*9);

    f=a+b+c+d+e+f;

    alert(f);

}

Upvotes: 0

Views: 315

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382404

When you do

f=a+b+c+d+e+f;

you're adding a few numbers to f, which is undefined. This makes NaN.

You probably want

f=a+b+c+d+e;

and maybe

return f;

at the end too.

Note that your function could be better written using a loop :

var f = 0;
for (var i=0; i<5; i++) f+=Math.floor(Math.random()*9); 

Upvotes: 6

Related Questions