Home >Web Front-end >JS Tutorial >Summary of 6 operators in JavaScript_Basic knowledge
JavaScript operators mainly include:
运算符 | 说明 | 例子 | 运算结果 |
---|---|---|---|
加 | y = 2 1 | y = 3 | |
- | 减 | y = 2-1 | y = 1 |
* | 乘 | y = 2*3 | y = 6 |
/ | 除,返回结果为浮点类型 | y = 6/3 | y = 2 |
% | 求余,返回结果为浮点类型 要求两个操作数均为整数 |
y = 6%4 | y = 2 |
递加,分为前加和后加 对布尔值和 NULL 将无效 |
y = 2 y(前加) y (后加) |
y = 3 | |
-- | 递减,分为前递减和后递减 对布尔值和 NULL 将无效 |
y = 2 --y(前减) y--(后减) |
y = 1 |
For pre-add and post-add, the result after execution is the variable plus 1. The difference is that the return result is different during execution. Please refer to the following two examples:
var y = 2;
alert(y); //Output: 2
alert(y); //Output: 3
The same goes for decreasing.
Assignment operator = is used for assignment operations. The assignment operator is used to assign the value on the right to the variable on the left. Set y = 6, see the table below:
运算符 | 例子 | 等价于 | 运算结果 |
---|---|---|---|
= | y = 6 | � | y = 6 |
= | y = 1 | y = y 1 | y = 7 |
-= | y -= 1 | y = y-1 | y = 5 |
*= | y *= 2 | y = y*2 | y = 12 |
/= | y /= 2 | y = y/2 | y = 3 |
%= | y %= 4 | y = y%4 | y = 2 |
Assignment operators can be nested:
Operator | Description | Example | Operation result | ||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
== | Equal | 2 == 3 | FALSE | ||||||||||||||||||||||||||||||||
=== | Identity (both values and types need to be compared) | 2 === 2
|
TRUE FALSE | ||||||||||||||||||||||||||||||||
!= | is not equal to, it can also be written as <> | 2 == 3 | TRUE | ||||||||||||||||||||||||||||||||
> | Greater than | 2 > 3 | FALSE | ||||||||||||||||||||||||||||||||
< | Less than | 2 < 3 | TRUE | ||||||||||||||||||||||||||||||||
>= | Greater than or equal | 2 >= 3 | FALSE | ||||||||||||||||||||||||||||||||
<= | Less than or equal | 2 <= 3 | TRUE |
Comparison operators can also be used for string comparisons.
Ternary can be regarded as a special comparison operator:
Syntax explanation: When expr1 evaluates to TRUE, the value of the entire expression is expr2, otherwise it is expr3.
Example:
This example determines whether the value of x is equal to 2. If x is equal to 2, then the value of y is equal to x (that is, equal to 2), otherwise y is equal to 1.
To avoid errors, it is a good idea to enclose each expression of the ternary operator in parentheses.
Operator | Description | Example | Operation result | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
&& | Logical AND | x = 2;
x && y > 5 | FALSE | ||||||||||||||||
|| | Logical OR | x = 2; y = 6; x && y > 5 | TRUE | ||||||||||||||||
! | Logical negation, take the opposite side of logic | x = 2; y = 6; !(x > y) | TRUE |