我想构建一个提示函数,它会提示直到用户输入一个值,然后返回该值。
当我进入强制模式然后输入一个值时,为什么此代码返回null?有人可以让它工作吗?
function UserInput(text, defaultText, mandantory) {
if (typeof defaultText === 'undefined')
defaultText = '';
if (typeof mandantory === 'undefined')
return prompt(text, defaultText);
else {
var a = prompt(text, defaultText);
if (a === '') {
return UserInput(text, defaultText, mandantory);
} else {
return null;
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
</body>
</html>
注意:必须从 onclick="..."调用它。
谢谢, 德扬
最佳答案
它正在返回null
因为您将其返回到您的 else
中如果输入了一个值。在你的最后else
您需要返回 a
而不是null
,当 a
与 ''
不同:
if (a === '') {
return UserInput(text, defaultText, mandantory);
} else {
return a;
}
注意:
要检查变量是否已定义,您可以使用 if(mandatory)
而不是写if(typeof mandantory === 'undefined')
.
演示:
function UserInput(text, defaultText, mandantory) {
if (typeof defaultText === 'undefined')
defaultText = '';
if (mandantory)
return prompt(text, defaultText);
else {
var a = prompt(text, defaultText);
if (a === '') {
return UserInput(text, defaultText, mandantory);
} else {
return a;
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
</body>
</html>
关于javascript - 递归提示函数返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022896/