0

It's a small game of guess number but why the parameter in javascript ii is NaN when i run the code below in google chorme? ii should be already a int type because i use the parseInt method

Snippet

//get a int number 1~100
let num = parseInt(Math.random() * 100) + 1;
let i = document.querySelector("input");
let sp = document.querySelector("span");
//get the input and span object
let ii = parseInt(i.value);
console.log(num);
let count = 0;

function send() {
  debugger
  count++;
  if (ii == num) {
    sp.innerText = "right" + count;
  } else if (ii > num) {
    sp.innerText = "too big";
  } else {
    sp.innerText = "too small";
  }
}
<input type="text" placeholder="input a int number 1~100">
<input type="button" value="guess the number" onclick="send()">
<h1>result:<span></span></h1>
Yogi
  • 6,241
  • 3
  • 24
  • 30
zfing
  • 3
  • 2
  • `let ii = parseInt(i.value);` will be `NaN` because the script is invoke immediately and `i.value` is `''` (thanks to Sebastian Simon for noticing that it's empty string and not undefined), hence `parseInt('')` returns `NaN` as intended. Move `let ii = parseInt(i.value);` inside the `send` function and everything will work as intended. – briosheje Dec 01 '22 at 09:14
  • Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Dec 01 '22 at 09:18
  • @SebastianSimon indeed, you're right. Still it's NaN – briosheje Dec 01 '22 at 09:18
  • oh thanks guys, i learn something so important, thanks all of you in advance!!! – zfing Dec 01 '22 at 09:25

0 Answers0