我试图评估输入是否为空字符串或不是数字在JavaScript中。

huangapple go评论66阅读模式
英文:

I am trying to evaluate if the input is an empty string or not a number in JavaScript

问题

我试图评估用户输入为空字符串(空字符串)或除数字以外的任何内容(非数字)时。在我控制台记录空字符串的输入后,返回了NaN。我不确定为什么else-if语句从未识别到,如果我测试空字符串或NaN值。这也最终影响了我的平均总分。

if (input !== getProduct()) {
    subtractPoint();
    incorrectGuess++;
} else if (input === '' || isNaN(input)) {
    console.log('Input value is empty or not a number', input);
} else {
    addPoint();
    correctGuesses++;
}

上述代码是您提供的JavaScript代码片段的一部分,其中包含了您提到的问题。在这段代码中,如果用户输入的是空字符串或NaN,会执行else-if分支中的代码块。

英文:

I am trying to evaluate when the user inputs nothing (an empty string) or anything besides a number (Not a number). After I console log the an input of empty string a NaN is returned. I am not sure why the else-if statement is never recognized if I test for both an empty string or NaN value. This also ultimately affects my average total score.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const equationTag = document.querySelector(&#39;div#equation&#39;);
const inputBtn = document.querySelector(&#39;input.submit-btn&#39;);
const incorrectTag = document.querySelector(&#39;p#incorrect&#39;);
const correctTag = document.querySelector(&#39;p#correct&#39;);
const counterTag = document.querySelector(&#39;div#counter&#39;);
const exitButton = document.querySelector(&#39;button.exit-btn&#39;);
const displayButton = document.querySelector(&#39;button.display-btn&#39;);
const resultModal = document.querySelector(&#39;section.stats-section&#39;);
const averageP = document.querySelector(&#39;p.avg&#39;);
const guessP = document.querySelector(&#39;p.total-guesses&#39;);

let points = 0;
let correctGuesses = 0;
let incorrectGuess = 0;
let totalGuesses = 0;

/*
    Takes a min and max value as parameters, and
    returns a randomized integer
*/
function getRandomValue(min, max) {
    let r = Math.floor(Math.random() * (max - min + 1)) + min;
    return r;
}

// Displays multiplcation equation on the user interface
function displayEquation() {
    equationTag.textContent = `${integerOne} x ${integerTwo}=`;
}

// Returns the product of the two integers
function getProduct() {
    return integerOne * integerTwo;
}
/* 
    Event listener grabs user input on click
    and clears user input afterwards
 */
inputBtn.addEventListener(&#39;click&#39;, () =&gt; {
    const inputTag = document.querySelector(&#39;#num&#39;);
    const answer = parseFloat(inputTag.value);
    evaluateAnswer(answer);
    inputTag.value = &quot;&quot;;
    inputTag.focus();
})

/* 
    Event listener grabs user input on enter key 
    and clears user input afterwards
*/
document.addEventListener(&quot;keydown&quot;, (event) =&gt; {
    if (event.key === &quot;Enter&quot;) {
        const inputTag = document.querySelector(&#39;#num&#39;);
        const answer = parseFloat(inputTag.value);
        evaluateAnswer(answer);
        inputTag.value = &quot;&quot;;
        inputTag.focus();
    }
})

exitButton.addEventListener(&#39;click&#39;, () =&gt; {
    setDisplayNone(resultModal);
})

displayButton.addEventListener(&#39;click&#39;, () =&gt; {
    setDisplayBlock(resultModal);
})

/*
    Takes a integer user input as an argument
    and compares whether the answer is correct or not.
*/
function evaluateAnswer(input) {
    console.log(&#39;Input value on eval &#39;, input); // double checking value
    if (input !== getProduct()) {
        subtractPoint();
        incorrectGuess++;
    } else if (input === &#39; &#39; || isNaN()) { // I am not sure why it&#39;s never evaluated
        console.log(&#39;Input value is empty or not a number &#39;, input);
    } else {
        addPoint();
        correctGuesses++;
    }
    totalGuesses++;
    restartGame();
    guessP.textContent = &quot;Incorrect Guesses= &quot; + incorrectGuess;
    let average = (correctGuesses / totalGuesses);
    let precisionAvg = roundToPrecision(average, 2);
    averageP.textContent = `${(precisionAvg * 100).toFixed(2)}%`;
    // console.log(&#39;Total guesses: &#39;, totalGuesses);
    // console.log(&#39;Incorrect &#39;, incorrectGuess);
    // console.log(&quot;Average: &quot;, average)
}

/*
    Evaluates if the points are less 
    than zero then restart points to 0
    else minus a point.
*/
function subtractPoint() {
    if (points &lt;= 0) {
        points = 0;
    } else {
        points -= 1;
    }
    setDisplayBlock(incorrectTag);
    setDisplayNone(correctTag);
    incorrectTag.textContent = (&#39;Incorrect: &#39; + integerOne + &#39; x &#39; + integerTwo + &#39; = &#39; + getProduct());
    setPoint();
}

// Sets new updated point
function setPoint() {
    counterTag.textContent = points;
}

// Adds a point and updates earned points
function addPoint() {
    points += 1;
    correctTag.textContent = (&#39;Correct!&#39;);
    setDisplayBlock(correctTag);
    setDisplayNone(incorrectTag);
    setPoint();
}

/*
    Resets game and gets two new random integers
    and calls the displayEquation function.
*/
function restartGame() {
    integerOne = getRandomValue(0, 12);
    integerTwo = getRandomValue(0, 12);
    displayEquation();
}

// sets css display block and opacity 1 on element
function setDisplayBlock(displayResult) {
    displayResult.style.display = &#39;block&#39;;
    displayResult.style.opacity = 1;
}

// sets css display none and opacity 0 on element
function setDisplayNone(displayResult) {
    displayResult.style.display = &#39;none&#39;;
    displayResult.style.opacity = 0;
}

/*
    Takes a value as a parameter, and integer as a parameter
    returns a rounded value with two decimal places at most
    https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary/11832950#11832950
*/
function roundToPrecision(value, decimals = 2) {
    const pow = Math.pow(10, decimals);
    return Math.round((value + Number.EPSILON) * pow) / pow;
}

// run game on load
let integerOne = getRandomValue(0, 12);
let integerTwo = getRandomValue(0, 12);
displayEquation(); 

<!-- language: lang-html -->

&lt;body&gt;

    &lt;header&gt;
        &lt;h1 id=&quot;title&quot;&gt;Multiply Me&lt;/h1&gt;
    &lt;/header&gt;

    &lt;main&gt;
        &lt;div id=&quot;equation&quot;&gt;&lt;/div&gt;
        &lt;div id=&quot;counter&quot;&gt;0&lt;/div&gt;
        &lt;input type=&quot;number&quot; id=&quot;num&quot; value=&quot;&quot; title=&quot;input&quot;&gt;

        &lt;input type=&quot;submit&quot; class=&quot;submit-btn&quot;&gt;
        &lt;button type=&quot;submit&quot; class=&quot;display-btn&quot; value=&quot;Show Results&quot;&gt;&amp;#x2b;&lt;/button&gt;

        &lt;div id=&quot;response&quot;&gt;
            &lt;p id=&quot;correct&quot;&gt;&lt;/p&gt;
            &lt;p id=&quot;incorrect&quot;&gt;&lt;/p&gt;
        &lt;/div&gt;

        &lt;section class=&quot;stats-section&quot;&gt;
            &lt;h3 class=&quot;h3-title&quot;&gt;Overall Results:&lt;/h3&gt;
            &lt;button class=&quot;exit-btn&quot;&gt;x&lt;/button&gt;

            &lt;article class=&quot;article-stats&quot;&gt;
                &lt;p class=&quot;total-guesses&quot;&gt;&lt;/p&gt;
                &lt;p class=&quot;avg&quot;&gt;&lt;/p&gt;
            &lt;/article&gt;

        &lt;/section&gt;


    &lt;/main&gt;

&lt;/body&gt;

<!-- end snippet -->

答案1

得分: 2

Several issues apart from not using isNaN correctly

You cannot see if a value is a single space after parseFloating it.

I would suggest

const answer = inputTag.value; 
evaluateAnswer(answer);

where you have this. Note the order and that I test the positive outcome before the negative

function evaluateAnswer(input) { 
  input = input.trim(); 
  if (input === "" || isNaN(input)) {   
    console.log('Input value is empty or not a number ', input);
    return; /* Any need to continue? */
  } else if (input === getProduct()) {
    addPoint();
    correctGuesses++;
  } else  {
    subtractPoint();
    incorrectGuess++;
  }
英文:

Several issues apart from not using isNaN correctly

You cannot see if a value is a single space after parseFloating it.

I would suggest

const answer = inputTag.value; 
evaluateAnswer(answer);

where you have this. Note the order and that I test the positive outcome before the negative

function evaluateAnswer(input) { 
  input = input.trim(); 
  if (input === &quot;&quot; || isNaN(input)) {   
    console.log(&#39;Input value is empty or not a number &#39;, input);
    return; /* Any need to continue? */
  } else if (input === getProduct()) {
    addPoint();
    correctGuesses++;
  } else  {
    subtractPoint();
    incorrectGuess++;
  }

答案2

得分: 1

你首先必须检查输入值是否不为空,因此你必须修改条件的顺序。最好在没有输入值时添加return以退出函数,以避免生成新的问题。

function evaluateAnswer(input) {
    console.log('在评估中的输入值', input); // 再次检查值
    if (input === '' || isNaN(input)) { // 我不确定为什么它从未被评估
        console.log('输入值为空或不是数字', input);
        return;
    } else if (input !== getProduct()) {
        subtractPoint();
        incorrectGuess++;
    } else {
        addPoint();
        correctGuesses++;
    }
    totalGuesses++;
    restartGame();
    guessP.textContent = "不正确的猜测= " + incorrectGuess;
    let average = (correctGuesses / totalGuesses);
    let precisionAvg = roundToPrecision(average, 2);
    averageP.textContent = `${(precisionAvg * 100).toFixed(2)}%`;
}
英文:

You must first check that the input value is not empty, so you must modify the order of the condition. And it is better to add a return to exit the function when no value is entered so that a new question is not generated.

function evaluateAnswer(input) {
    console.log(&#39;Input value on eval &#39;, input); // double checking value
    if (input === &#39;&#39; || isNaN(input)) { // I am not sure why it&#39;s never evaluated
        console.log(&#39;Input value is empty or not a number &#39;, input);
        return;
    } else if (input !== getProduct()) {
        subtractPoint();
        incorrectGuess++;
    } else{
        addPoint();
        correctGuesses++;
    }
    totalGuesses++;
    restartGame();
    guessP.textContent = &quot;Incorrect Guesses= &quot; + incorrectGuess;
    let average = (correctGuesses / totalGuesses);
    let precisionAvg = roundToPrecision(average, 2);
    averageP.textContent = `${(precisionAvg * 100).toFixed(2)}%`;
}

huangapple
  • 本文由 发表于 2023年2月6日 03:57:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定