gpt4 book ai didi

javascript - 刽子手游戏检查猜测类型是否不是字符串不起作用

转载 作者:行者123 更新时间:2023-11-30 15:30:07 24 4
gpt4 key购买 nike

这是刽子手游戏。这是一款来自 js book 的简单游戏,适合初学者。我尝试对用户输入的内容添加更多检查。我输入了 else if typeof guess !== 'string' 但不起作用。

当我输入数字或符号时 # 代码进入 -- one more life: guessesNr--,而不是 alert("Please enter a single letter!");

请有人告诉我该怎么做,因为我不知道为什么不符合我的逻辑。

var words = [
"javascript",
"monkey",
"amazing",
"pancake"
];

var word = words[Math.floor(Math.random() * words.length)];

//create an empty array called answerArray and fill it
//with underscores (_) to match the number
//of letters in the word
var answerArray = [];

for( var i=0; i < word.length; i++) {
answerArray[i] = "_";
}

//every time the player guesses a
//correct letter, this value will
//be decremented (reduced) by 1
var remainingLetters = word.length;
var guessesNr = 4;
var isHit = false;

while((remainingLetters > 0) && (guessesNr > 0)) {
// Show the player their progress
alert("The word is from " + word.length + " letters " + answerArray.join(" "));
// Take input from player
var guess = prompt("Guess a letter");

// if the player clicks the Cancel button, then guess will be null
if(guess===null) {
// break to exit the loop
break;
//ensuring that guess is exactly one letter
} else if(guess.length !== 1) {
alert("Please enter a single letter!");
} else if(typeof guess !== 'string') {
alert("Please enter only letters!");
} else {
for(var j = 0; j < word.length; j++) {
if(word[j] === guess) {
// sets the element at index j, from word,
// of answerArray to guess
answerArray[j] = guess;
remainingLetters--;
isHit = true;

}
}
if(!isHit) {
guessesNr--;
alert("You have " + guessesNr + " more lives");
if(guessesNr === 0) {
alert("No more lives");
break;
}

}

}

}

//alert(answerArray.join(" "));
alert("Great job! The answer was " + word);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>

最佳答案

“prompt”的返回值是一个字符串。一个字符串几乎可以包含任何字符,包括字母、符号和数字。在您的例子中,您正在检查一个字符串,而不是字母。所以:

  • "abcd1234"是一个字符串;
  • 1234 是一个整数(注意没有引号):typeof 1234 == "number"
  • “1234”是一个字符串。 typeof "1234"== "string"

因此您应该检查一个仅由字母组成的字符串。有许多可能的方法可以做到这一点,您可以使用正则表达式轻松地做到这一点,例如:

var letters = /^[A-Za-z]+$/;
if (!guess.match(letters)) alert("Please enter only letters!");

如果你只想要一个字母,试试同样的方法:

var letters = /^[A-Za-z]$/;

正则表达式非常强大,我的建议是您阅读更多关于它们的内容。希望我有所帮助!

关于javascript - 刽子手游戏检查猜测类型是否不是字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42378551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com