JavaScript comparison and logical operators
Comparison operator
Operator Description Example Operation Result
##== Equal to 2 == 3 FALSE === Constantly equal (both values and types are compared) (2 === 2 TRUE) (2 === "2" FALSE ) != Not equal to, can also be written as <> 2 == 3 TRUE > Greater than 2 > 3 FALSE < Less than 2 < 3 TRUE >= Greater than or equal to 2 >= 3 FALSE <= Less than or equal to 2 <= 3 TRUEComparison operators can also be used for string comparisons.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var a=5,b="5"; document.write(a==b); document.write("<br />"); document.write(a===b); document.write("<br />"); document.write(a!=b); document.write("<br />"); document.write(a!==b); </script> </head> <body> </body> </html>
##Logical operators
Operator
ExplanationExample Operation result
#&& Logical AND (and) x = 2 ; y = 6; x && y > 5 FALSE || Logical OR (or) x = 2; y = 6; , take the opposite side of logic x = 2; y = 6; !(x > y) TRUE<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var a=5,b="5"; document.write(a&&b > 10); document.write("<br />"); document.write(a||b <6); document.write("<br />"); document.write(!(a>b)); </script> </head> <body> </body> </html>
Conditional Operator
JavaScript also includes conditional operators that assign values to variables based on certain conditions.
Syntax
variablename=(condition)?value1:value2
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> 年龄:<input id="age" value="18" /> <p>是否达到上学年龄?</p> <button onclick="myFunction()">点击按钮</button> <p id="demo"></p> <script> function myFunction() { var age,voteable; age=document.getElementById("age").value; voteable=(age<7)?"年龄太小,继续幼儿园":"年龄已达到,可以入学"; document.getElementById("demo").innerHTML=voteable; } </script> </body> </html>