Home >Web Front-end >JS Tutorial >JS compares the size of two numerical values instance
Generally:
if(2 > 10) { alert("不正确!"); }
This comparison will not be the desired result: it is equivalent to 2 >1, take out the first digit of 10 and compare.
Solution:
if(eval(2) > eval(10)) { alert("不正确!"); }
The eval() function is used to evaluate a code string without referencing any specific object.
<script> function check() { var num1=document.form1.num1.value; var num2=document.form1.num2.value; if(num2>num1) <!-错误写法--> { alert('num2 > num1!'); return false; } return true; } </script> <script> function check() { var num1=document.form1.num1.value; var num2=document.form1.num2.value; if(parseInt(num2)>parseInt(num1)) <!-正确写法(转换成INT)--> { alert('num2 > num1!'); return false; } return true; } </script>
EG:
110 and 18 are 18 in the program you wrote, because
these two numbers are both strings, and after 1 and 1 are equal, compare 1 and 8, of course 8 is big, so 18 is big
You convert it to INT type before comparison
if(parseInt(num2)>parseInt(num1))