JS - 运算符
一、算术运算符
用于执行数学运算。
运算符 | 描述 | 示例 | 结果 |
---|---|---|---|
| 加法 |
|
|
| 减法 |
|
|
| 乘法 |
|
|
| 除法 |
|
|
| 取模(余数) |
|
|
| 指数(幂) |
|
|
| 自增(前/后) |
|
|
| 自减(前/后) |
|
|
注意:自增/自减的前后区别
let a = 5;
console.log(a++); // 5(先返回值,后自增)
console.log(a); // 6let b = 5;
console.log(++b); // 6(先自增,后返回值)
console.log(b); // 6
二、赋值运算符
用于给变量赋值。
运算符 | 示例 | 等价于 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let x = 10;
x += 5; // x = 10 + 5 = 15
x *= 2; // x = 15 * 2 = 30
console.log(x); // 30
三、比较运算符
用于比较两个值,返回布尔值(true
或 false
)。
运算符 | 描述 | 示例 | 结果 |
---|---|---|---|
| 相等(值相等) |
|
|
| 严格相等(值和类型都相等) |
|
|
| 不相等 |
|
|
| 严格不相等 |
|
|
| 大于 |
|
|
| 小于 |
|
|
| 大于等于 |
|
|
| 小于等于 |
|
|
重要建议:始终使用 ===
和 !==
,避免类型转换带来的意外结果。
四、逻辑运算符
用于组合或操作布尔值。
运算符 | 描述 | 示例 | 结果 |
---|---|---|---|
| 逻辑与(AND) |
|
|
` | ` | 逻辑或(OR) | |
| 逻辑非(NOT) |
|
|
| 空值合并(ES2020) |
|
|
短路求值(重要特性):
// && 短路:如果第一个为false,直接返回第一个值,不计算第二个
false && console.log("这行不会执行");// || 短路:如果第一个为true,直接返回第一个值,不计算第二个
true || console.log("这行不会执行");// 实际应用:条件执行
const user = null;
const username = user && user.name; // 如果user为null,直接返回null,不会报错
const displayName = user?.name || "匿名用户"; // 常用模式:提供默认值
五、三元运算符
条件运算符,是 if-else
的简写形式。
语法:条件 ? 值1 : 值2
const age = 20;
const status = age >= 18 ? "成年人" : "未成年人";
console.log(status); // "成年人"// 等价于:
let status;
if (age >= 18) {status = "成年人";
} else {status = "未成年人";
}
六、其他重要运算符
1. 类型运算符
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object"(历史遗留问题)
typeof [] // "object"
typeof {} // "object"
typeof function(){} // "function"
2. 空值合并运算符 ??
(ES2020)
与 ||
类似,但只对 null
或 undefined
生效:
0 || "默认值" // "默认值"(0被视为false)
0 ?? "默认值" // 0(0不是null或undefined)"" || "Hello" // "Hello"(空字符串被视为false)
"" ?? "Hello" // ""(空字符串不是null或undefined)
3. 可选链运算符 ?.
(ES2020)
安全地访问嵌套对象属性:
const user = {profile: {name: "Alice"}
};// 传统方式(需要多次检查)
const name = user && user.profile && user.profile.name;// 使用可选链
const name = user?.profile?.name; // "Alice"// 即使属性不存在也不会报错
const job = user?.profile?.job; // undefined(而不是报错)
七、运算符优先级
当表达式中有多个运算符时,优先级决定了执行顺序(类似于数学中的先乘除后加减)。
从高到低常见优先级:
()
(括号)++
--
(自增/减)*
/
%
+
-
<
<=
>
>=
==
!=
===
!==
&&
||
=
+=
-=
(赋值)
最佳实践:使用括号 ()
明确优先级,避免依赖记忆。
// 模糊的优先级
const result = 5 + 3 * 2; // 11(不是16)// 明确的优先级
const result = (5 + 3) * 2; // 16
总结
掌握这些运算符是JavaScript编程的基础。特别要注意:
比较运算符:优先使用
===
和!==
逻辑运算符:理解短路求值的特性
现代运算符:掌握
??
和?.
的使用场景优先级:不确定时使用括号明确意图