当我使用 inputName 函数测试字符串时,我陷入了一个无限循环,该循环不断在浏览器中显示 alert() 函数。我不确定为什么会发生这种情况背后的逻辑。请注意,这是针对学校作业的,我需要使用 for 循环和带参数的函数来测试名为 employeeName 的输入数据。该函数在返回值之前测试数据是否为空、空或数字。
<html>
<head>
<script type="text/javascript">
function inputName(name)
{
var flag;
do
{
flag = false;
if (name == null)
{
alert("You have hit the 'Cancel' button!");
return name;
flag = false;
}
if (name == "")
{
alert("You tried entering no name!");
flag = true;
}
else if (!isNaN(name))
{
alert("You tried entering a number!");
flag = true;
}
else if (name.length < 2)
{
alert("You tried entering a name less than 2 characters!");
flag = true;
}
} while (flag);
return name;
}
</script>
</head>
<body>
<script type="text/javascript">
// DECLARATIONS
var numEmployees;
var employeeName;
var testName;
// INPUT
numEmployees = prompt("Enter the number of employees");
// PROCESSING
for (var index = 1; index <= numEmployees; index++)
{
employeeName = prompt("Enter a name.");
testName = inputName(employeeName);
}
// OUTPUT
</script>
</body>
</html>