Home  >  Article  >  Web Front-end  >  JS compares the size of two numerical values ​​​​instance

JS compares the size of two numerical values ​​​​instance

高洛峰
高洛峰Original
2016-12-05 11:46:441972browse

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(&#39;num2  >  num1!&#39;); 
 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(&#39;num2  >  num1!&#39;); 
 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))


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn