JavaScript comp...LOGIN

JavaScript comparison and logical operators

Comparison and logical operators are used to test true or false.


Comparison operators

Comparison operators are used in logical statements to determine Whether variables or values ​​are equal.

Given x=5, the following table explains the comparison operators:

##>= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true
OperatorDescriptionExample
== is equal tox==8 is false
=== Congruent (value and type)x===5 is true; x==="5" is false
!= is not equal to x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
How to use

You can use comparison operators in conditional statements to compare values ​​and then take action based on the results:

if (age<18) document.write("Too young");


We will introduce more about it in the following chapters Knowledge of conditional statements.


Logical Operators

Logical operators are used to determine the logic between variables or values.

Given x=6 and y=3, the following table explains the logical operators:

OperatorDescriptionExample&&and(x < 10 && y > 1) is true||or(x==5 || y==5) is false!not!(x==y) is true

Conditional operators

JavaScript also includes conditional operators that assign values ​​to variables based on certain conditions.

Syntax

variablename=(condition)?value1:value2

Example

If the value in the variable age is less than 18, assign the value "age is too young" to the variable voteable, otherwise assign the value "age has reached".

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>php中文网(php.cn)</title>
</head>
<body>
<p>点击按钮检测年龄。</p>
年龄:<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<18)?"年龄太小":"年龄已达到";
        document.getElementById("demo").innerHTML=voteable;
    }
</script>
</body>
</html>

Run the program and try it



Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击按钮检测年龄。</p> 年龄:<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<18)?"年龄太小":"年龄已达到"; document.getElementById("demo").innerHTML=voteable; } </script> </body> </html>
submitReset Code
ChapterCourseware
    None