0

I just can't figure out where the problem is to ask user to insert a number and judge if it's prime, it will be great help since it's my second day learning JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>Prime Checker</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var i; result = true;
var n1 = prompt("Please insert a number, I'll check if it's a prime!" , "");
n1 = Number(n1);
if(isNaN(n1))
{
    alert("You didn't insert a number, please check again!");
}
else
{
    alert("I will check right now");
}
for(i = 2; i < n1; i++)
{
   if(n1 % i == 0)
    {
    result = false;
    break;
    }
}
if(result == true)
{
alert(n1 "is a prime");
}
else
{
alert(n1 "is not a prime")
}
</script>
</head>
<body>
</body>
</html>
4

2 回答 2

2

有一个很棒的工具叫做jsfiddle会有所帮助——我也推荐使用 Chrome 开发工具或 Firefox 的 Firebug。

是一个有效的 JS Fiddle - 你非常接近。问题是你的 JS 甚至没有编译。你有几行接近尾声:

alert(n1 "is not a prime")

应该

alert(n1 + " is not a prime")

即使 isNan 为真,你仍然会执行你的 for 循环。

于 2013-05-25T20:30:25.390 回答
0

语法错误。这个:

alert(n1 "is a prime");

应该:

alert(n1 + " is a prime");

其他警报也一样。

于 2013-05-25T20:30:08.270 回答