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

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

高洛峰
Release: 2016-12-05 11:46:44
Original
2107 people have browsed it

Generally:

if(2 > 10)
{
alert("不正确!");
}
Copy after login

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("不正确!");
}
Copy after login

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>
Copy after login

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))


Related labels:
js
Statement of this Website
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
Latest Issues
Where is js written?
From 1970-01-01 08:00:00
0
0
0
js file code not found
From 1970-01-01 08:00:00
0
0
0
js addClass not working
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template