javascript - How to check 2 different types of things using ===? -


i want check whether value in input box equal variable. when use ===, returns false when use ==, returns true, provided both equal.

<input id="g1"></input> <button id="b" onclick="myfunction()">try</button> function myfunction() { var d1; d1 = math.floor(math.random()*100) if( document.getelementbyid("g1").value ==  d1) { document.getelementbyid("d").innerhtml = "correct"; } 

this happens because javascript == can compare numeric strings numbers whereas === not.

similarly "value" property using returns string you're comparing integer. you'll need use parseint convert value first.

parseint(document.getelementbyid("g1").value) ===  d1 

a few things consider parseint:

  • parseint returns nan when try convert non-number strings (i.e. converting 'bogus' returns nan.
  • it convert decimals integers dropping decimals. parseint('2.1') == 2 // => true.

honestly, given use case, it's appropriate use ==, i'd add comment explaining why it's being used.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -