输出为undefined / NAN

时间:2015-05-10 10:18:56

标签: javascript nan

有人会为什么我的程序输出undefined或NAN?我确定我的随机数发生器正在工作。此外,当数字生成器生成值10次时,我试图总结所有“得分”值。谢谢你的帮助

<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
	{
	randomnumber()
	totalscore()
	}
function randomnumber()
{
	var randomnumber;
	randomnumber = Math.random()*3;
	return(Math.floor(randomnumber+0.5));

}
function totalscore() 
{
	var n;
	var score;
	var number;
	number = randomnumber()
	for (n=0;n<11; n=n+1)
	{
		if (number==0)
			{
			score =score+0
			}
		if (number==2)
			{
			score =score+2
			}
		if (number==3)
			{
			score =score+3
			}
		document.write(score)
	}
}

</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()"> 
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>

3 个答案:

答案 0 :(得分:1)

因为score变量是undefined。您应该使用数字初始化它,例如:var score = 0;

答案 1 :(得分:1)

您需要将您的score变量初始化为0.直到您没有,它的值为undefined,当您对未定义的对象进行数学运算时,您将会得到NaN错误。我还格式化了你的代码。

<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
    {
    randomnumber()
    totalscore()
    }
function randomnumber()
{
    var randomnumber;
    randomnumber = Math.random()*3;
    return(Math.floor(randomnumber+0.5));

}
function totalscore() 
{
    var n;
    var score = 0;
    var number = randomnumber();
    for (n = 0 ; n < 11 ; ++n)
    {
        if (number == 0){
            score += 0;
        }
        else if (number == 2)
        {
            score += 2;
        }
        else if (number == 3)
        {
            score += 3;
        }
        document.write(score)
    }
}

</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()"> 
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>

编辑:如果我理解你的评论,你应该做这样的事情

function totalscore() 
{
    var n;
    var score = 0;
    for (n = 0 ; n < 10 ; ++n)
    {
        score += randomnumber();
        document.write(score)
    }
    var grandTotal = score;
}

答案 2 :(得分:1)

变量scoretotalscore函数中声明但从未初始化。向undefined添加任何内容会产生NaN,这是您的函数写入页面的内容。