### javascript 中的运算符
javascript 中的运算符是用于对值和变量执行运算的特殊符号。这些操作可以涉及算术、赋值、比较、逻辑和其他操作。了解运算符对于执行基本计算、比较和控制代码流程至关重要。
javascript 支持多种运算符,它们分为以下类型:
### 1. **算术运算符
**
算术运算符用于对数字进行数学计算。1
2
3
4
5
6
7
8
let a = 10;
let b = 2;
console.log(a + b); // output: 12
console.log(a - b); // output: 8
console.log(a * b); // output: 20
console.log(a / b); // output: 5
console.log(a % b); // output: 0
console.log(a ** b); // output: 100
**
2. 赋值运算符**
赋值运算符用于为变量赋值。
立即学习“Java免费学习笔记(深入)”;
1
2
3
4
let x = 10;
x += 5; // x = x + 5 -> 15
x *= 2; // x = x * 2 -> 30
console.log(x); // output: 30
### 3. **比较运算符
**
比较运算符用于比较值并根据条件返回布尔值(true 或 false)。1
2
3
4
console.log(5 == 5); // output: true (loose comparison)
console.log(5 === 5); // output: false (strict comparison)
console.log(10 > 5); // output: true
console.log(3 <= 2); // output: false
### 4. **逻辑运算符
**
逻辑运算符用于执行逻辑运算,返回布尔值。#### 示例:
1
2
3
4
5
let a = true;
let b = false;
console.log(a && b); // output: false
console.log(a || b); // output: true
console.log(!a); // output: false
### 5. **一元运算符
**
一元运算符对单个操作数进行运算以执行特定操作。#### 示例:
1
2
3
4
let x = 10;
console.log(++x); // output: 11 (pre-increment)
console.log(x--); // output: 11 (post-decrement)
console.log(typeof x); // output: number
*#### 示例:
*
1
2
3
let age = 18;
let result = age >= 18 ? adult : minor;
console.log(result); // output: adult
### 7. **位运算符 **按位运算符对二进制数进行运算。
*#### 示例:
*
1
2
3
4
5
let a = 5; // binary: 101
let b = 3; // binary: 011
console.log(a & b); // output: 1 (binary: 001)
console.log(a | b); // output: 7 (binary: 111)
console.log(a << 1); // output: 10 (binary: 1010)
### 8. **扩展运算符 (...) **扩展运算符允许您将数组或对象中的元素解压到新的数组或对象中。
*#### 示例:
*
1
2
3
4
5
6
7
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 };
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }
### 结论
javascript 运算符是执行计算、比较和逻辑运算的基础。无论您是操纵值、比较它们还是控制程序流程,理解这些运算符对于高效编码都至关重要。根据您的任务使用正确的运算符,以确保代码干净且可读。
嗨,我是 abhay singh kathayat!
我是一名全栈开发人员,拥有前端和后端技术方面的专业知识。我使用各种编程语言和框架来构建高效、可扩展且用户友好的应用程序。
请随时通过我的商务电子邮件与我联系:kaashshorts28@gmail.com。以上就是了解 JavaScript 运算符:带有示例的完整指南的详细内容,更多请关注php中文网其它相关文章!