在我的测试脚本中,我运行了 if 语句,但我从未运行过其他语句?我做错了什么

In my test script I get my if statment run but I never get the else to run? What I am doing wrong

本文关键字:运行 语句 其他 什么 错了 我的 测试脚本 if      更新时间:2023-09-26

如果您运行此脚本并在提示框中输入 2,它永远不会运行其他脚本,我不知道为什么。是我设置 var 或 myFunction 的方式不正确吗?

<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var x=1;
var name=prompt("Please enter a number one");
if ( x===1)
  {
alert("good");
  }
else 
  {
alert("not a number 1");
  }
} 
</script>
</body>
</html>
我相信

你想检查x == name.

您正在检查x === 1这始终是正确的,因为您已经设置了x = 1并且从未覆盖它。

此外,x === name不起作用,因为prompt返回一个字符串,而1是一个数字。您可能需要设置x = '1'然后检查x === name是否要使用严格比较。

你永远不会将 x 分配给除 1 之外的任何内容!然后你检查它确实是整数 1。

将脚本更改为

if (prompt("Please enter a number one") != 1){
    alert('Not a number 1');
} else {
    alert('Good')
}

因为您要在脚本中定义x=1,然后检查x === 1

也许你的意思是将用户输入分配给x,但你没有这样做。

或者正如zzzzBov所说,也许你打算根据你的目的做x === namex == name