JavaScript操作符是用来对操作数进行运算的符号。
它们是诸如加法+、乘法*、减法-等等。
在JavaScript中,我们有不同类型的运算符,例如
- 算术运算符
- 赋值运算符
- 比较(关系)运算符
- 逻辑运算符
- 特殊运算符
算术运算符
算术运算符用于在变量和/或数值之间进行算术。
let y = 5;
let x = y + 2;
console.log(x); // it wil return 7
同样地,我们可以使用不同的运算符进行计算,如乘法、减法和除法。也有一些特殊的运算符,如:
指数 运算符
这是一个来自(ES6)的更新的运算符。
let y = 2;
let x = y ** 2;
console.log(x); // it will return 4;
递增
递增符号显示为++
let y = 5;
let x = ++y;
console.log(x); // it will return 6
console.log(y); it will return 6
注意,这里两个变量都会受到影响。递减操作符的作用与此相同。
赋值操作符
一些赋值运算符是这样的。
● =
● +=
● -=
● *=
● %=
赋值运算符的例子在下面提到。
● let x = 10;
let y = 5;
x = y;
console.log(x) // it will return 10
● let x = 10;
let y = 5;
x += y;
console.log(x); // it will return 15
● let x = 10;
let y = 5;
x *= y;
console.log(x); // it will return 15
●let x = 10;
let y = 5;
x %= y;
console.log(x); // it will return the 15
同样,我们也可以使用上述赋值运算符
比较(关系)运算符
比较运算符用于逻辑语句中,以确定变量或数值之间的相等或不同。
X = 5;
console.log(x == 8); // returns false
X = 5
console.log(x == 5) // returns true
X = 5
console.log(x === “5”) ; // returns false as three equal to check for the data type as well. If x is integer 5 or string 5 , So it returns false.
X = 5
console.log(x != 8) // returns true as this stands for not equal to ,So it returns true.
X = 5
console.log(x ! ===”8”)// returns true. Here it stands for not equal to and not equal data type.
X = 5
console.log(x > 8) ; // returns false ,it stands for greater than.
X = 5
console.log(x >= 8); // it returns false as it checks is variable is greater than ir equal to.
逻辑运算符
逻辑运算符用于确定变量或值之间的逻辑关系。逻辑运算符包括
● && and
||或
●!不
下面是提到的例子
let x = 6;
let y = 3;
console.log(x < 10 && y > 1); // return true as variable x is less than 10 and variable y is greater than 1.
let x = 6;
let y = 3;
console.log(x == 5 || y == 5); // returns false as variable x is not equal to 5 and variable y is not equal to 5. Here we are using || or condition to check the values of both the variables at once.
let x = 6;
let y = 3;
console.log(!x === y) // return true
NOT运算符(!)对假的语句返回真,对真的语句返回假。
特殊运算符
下面是js中的一些特殊运算符的例子
三元运算符
这个操作符可以作为if语句的一个快捷方式。如果条件为真,它返回expr1的值;如果条件为假,它返回expr2的值。
Condition ? exp1 : exp2
逗号运算符(,)
exp1,exp2
该操作符评估两个表达式并返回exp2的值。该操作符可用于将多个表达式放在一个语句中。
空值运算符(??)
如果第一个参数是空的或未定义的,??运算符返回第一个参数。否则它将返回第二个参数。
let a = 3
let b = null
console.log(a ?? b) // it returns 3 as it replaces the b null value with a value 3 .
let a = undefined
let b = 3
console.log(a ?? b ) // it returns 3 as it replaces the value of undefined with 3 .