简体   繁体   English

在JS中正确使用typeof运算符?

[英]Using typeof operator in JS correctly?

I am making a simple hangman game in JavaScript. 我正在用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"). 我正在尝试添加新功能,我想添加的功能之一是检查用户提供的输入(当他们猜出未知单词的字母时),以确保它实际上是字母数字输入(或者我的目的是检查输入的内容不是“!”这样的符号还是“ 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. 我找到了typeof运算符,但似乎我要检查的字符类型已通过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"). 当我在Chrome的开发工具中运行该代码时,我可以输入“ 2”,并且它永远不会给我警报,它不会崩溃,也不会重新启动循环(这是我之前的现状)尝试实现此“功能”)。

Thanks in advance! 提前致谢!

The issue with this code is that prompt always returns a string value. 此代码的问题是prompt总是返回一个string值。 These values may or may not be able to be converted to a Number ; 这些值可能或不能被转换为Number ; this conversion would be performed using parseInt or parseFloat . 此转换将使用parseIntparseFloat执行。 (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. (如果字符串可以转换为数值,则这些方法将返回该值;否则,它们将返回NaN 。)但是, typeof执行任何插值操作-它声明变量的类型(存在时),而不是变量所针对的类型。可能会被转换。 Therefore, typeof guess will always evaluate to string . 因此, typeof guess将始终评估为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). 要检查字符串是否包含数值,可以使用条件if (!isNaN(parseInt(guess))if (!isNaN(parseFloat(guess)) (请注意,必须使用isNaN方法代替传统的等式校验)。

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 ç . 同样,如果您的answerArray仅包含不带变音符号的拉丁字母,则您可能想禁止猜测éç等字符。 Thus, consider using RegEx to check if the guessed string contains an acceptable letter. 因此,考虑使用RegEx检查猜测的字符串是否包含可接受的字母。 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]/)) . 就像在这篇Stack Overflow帖子中一样 ,您可以使用以下if语句来确保字符串长一个字符且是有效字母: 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). 您可以参考该帖子,了解解决更复杂的字符集的方法(例如,非拉丁字母或带有变音符号的字符集)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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