JavaScript comparisons, logical operators, and operators

General comparison and logical operators are used to test  true  or  false .

1. Comparison operators

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

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

operator describe Compare return value
== equal x==8 false
x==5 true
=== Absolute equality (both value and type are equal) x==="5" false
x===5 true
!= not equal to x!=8 true
!== Not absolutely equal (one or both of the value and the type are not equal) x!=="5" true
x!==5 false
> more than the x>8 false
< less than x<8 true
>= greater or equal to x>=8 false
<= less than or equal to x<=8 true

You can use comparison operators in conditional statements to compare values.

2. Logical operators

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

Assuming that x=6 and y=3 are given, the following table explains the logical operators:

operator describe example
&& and (x < 10 && y > 1) One true
|| or (x==5 || y==5) is false
! not !(x==y) is true

conditional operator

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

grammar

variablename=(condition)?value1:value2 

Example:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title></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>

Illustration:

Click the button below to show that the age has reached

3.JS arithmetic operators

Arithmetic operations between AND/OR values.

Assuming y=5, the following table explains these arithmetic operators:

operator describe example x operation result y operation result
+ addition x=y+2 7 5
- Subtraction x=y-2 3 5
* multiplication x=y*2 10 5
/ division x=y/2 2.5 5
% Modulo (remainder) x=y%2 1 5
++ self-increasing x=++y 6 6
x=y++ 5 6
-- Decrease x=--y 4 4
x=y-- 5 4

JS assignment operator

The assignment operator is used to assign values ​​to JavaScript variables.

Assuming that x=10  and  y=5 are given  , the following table explains the assignment operators:

operator example Equivalent to Operation result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

Add strings and numbers

If two numbers are added, the sum of the numbers is returned. If a number is added to a string, a string is returned.

x=5+5;
y="5"+5;
z="Hello"+5;

The printed result is:

10
55
Hello5

The above content is summarized by me in the novice tutorial. If you don’t understand, you can leave a comment!

Guess you like

Origin blog.csdn.net/He_9a9/article/details/132662323