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:
parseintreturnsnanwhen try convert non-number strings (i.e. converting'bogus'returnsnan.- 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
Post a Comment