当我使用 inputName 函数测试字符串时,我陷入了无限循环,该循环不断在浏览器中显示alert() 函数。我不确定发生这种情况背后的逻辑。请注意,这是一项学校作业,我需要使用 for 循环和带有参数的函数来测试名为“employeeName”的输入数据。该函数在返回值之前测试数据是否为 null、空或数字。
<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>
最佳答案
因为您没有在循环内提示输入新名称,所以该名称永远不会改变,因此您可以一遍又一遍地测试相同的字符串。
关于javascript - 在 for 循环中使用函数测试字符串时,我总是陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19936947/