简体   繁体   中英

Using typeof operator in JS correctly?

I am making a simple hangman game in JavaScript. I'm playing around trying to add new features and one of the features I'd like to add is to check the input the user gives (when they guess a letter of the unknown word) to make sure it is in fact an alphanumeric input (or my intention is to check that the input isn't a symbol like "!" or a number like "5").

I know I could probably use a global variable that contains all the valid characters and check the input against those characters but I was wondering if there is a built in method for this. I found the typeof operator but it seems that the types of characters I'm checking for get converted to strings by JavaScript.

The loop in which I'm trying to implement this:

while (remainingLetters > 0 && numberOfGuesses > 0) {
alert(answerArray.join(" "));
alert("You have " + numberOfGuesses + " guesses remaining.");

var guess = prompt("Guess a letter, or click \
'Cancel' to stop playing.").toLowerCase();

if (guess === null) {
  break;
} else if (typeof guess === "number") {
  alert("Please enter a single LETTER.");
} else if (guess.length !== 1) {
  alert("Please enter a single letter.");
} else {
  for (var j = 0; j < word.length; j++) {
    if (word[j] === guess) {
      answerArray[j] = guess;
      remainingLetters--;

// there is some code missing here that I'm pretty sure is not essential 
// to my question!

When I run that in Chrome's dev tools, I can input "2" and it never gives me the alert I'm looking for - it doesn't crash or anything it just re-starts the loop (which is the status quo before I tried to implement this "feature").

Thanks in advance!

The issue with this code is that prompt always returns a string value. These values may or may not be able to be converted to a Number ; this conversion would be performed using parseInt or parseFloat . (If the string can be converted to a numerical value, these methods return that value; otherwise, they return NaN .) However, typeof performs no interpolation—it states the type of the variable as it exists, and not any types to which it could potentially be converted. Therefore, typeof guess will always evaluate to string . To check if a string contains a numerical value, you could use the condition if (!isNaN(parseInt(guess)) or if (!isNaN(parseFloat(guess)) (note that the isNaN method must be used instead of a traditional equality check).

However, you might want to structure your checks around ensuring that the entry is a letter rather than accounting for the myriad ways in which it might not be. For instance, @ and are not numbers, but they are also not letters. Similarly, if your answerArray contains only Latin letters without diacritics, you might want to disallow guesses of characters like é and ç . Thus, consider using RegEx to check if the guessed string contains an acceptable letter. As in this Stack Overflow post , you can use the following if statement to ensure that the string is one character long and is a valid letter: if (str.length === 1 && str.match(/[az]/)) . You can refer to that post for ways of addressing more complicated character sets (eg, non-Latin letters or those with diacritics).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM