似乎是个很容易解决的问题。无法理解为什么代码将返回秘密词,尽管输入空格或字符太多/太少。需要一点帮助。谢谢!
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
<!--variable to hold secret word-->
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
do {
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length < 6) {
window.alert("secret word is too short");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length > 6) {
window.alert("secret word is too long")
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user_prompt.indexOf('') >= 0) {
window.alert("secret word cannot contain spaces");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
}
while(user_prompt != -999);
}发布于 2015-03-05 16:04:14
除了你的排版(user_prompt != user.prompt),你正在寻找一个没有空格的7个字符字符串。
这个条件检查的是:
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {是一个包含任何字符的6个字符字符串。
你所需要的是:
if(user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {如果字符串长度为7,且没有空格,则为真。
下面是一个工作示例,我将其简化了一些,这样在这里的片段中使用起来就更容易了,但是您可以看到并重用这些条件:
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
document.getElementById("guess").innerHTML = '';
if (user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
document.getElementById("guess").innerHTML = text + "<br>" + user_prompt + "<br>" + output;
} else if (user_prompt.length < 7) {
document.getElementById("guess").innerHTML = "secret word is too short";
} else if (user_prompt.length > 7) {
document.getElementById("guess").innerHTML = "secret word is too long";
} else if (user_prompt.indexOf(' ') >= 0) {
document.getElementById("guess").innerHTML = "secret word cannot contain spaces";
}
}<div id="guess"></div>
<button onclick="secretWord()">Run</button>
发布于 2015-03-05 16:03:23
else if(user.prompt.length < 6) {
// ...
else if(user.prompt.length > 6) {在这两种情况下,user.prompt.length都应该是user_prompt.length
发布于 2015-03-05 16:04:17
你的问题就在“如果”语句中
应该是user_prompt而不是user.prompt
此外,即使你输入的字符数量完全正确的6左右,它将通过第一个如果测试。您不是在检查空间,即' ',而是''。注意检查空格是否正确。
https://stackoverflow.com/questions/28882210
复制相似问题