运算符
JavaScript 运算符是真的多,尤其是 ES6 之后还在不停的加运算符,其他编程语言看 JS 就像怪物一样,各种骚操作不断~~
运算符分类
1、算术运算符
算术运算符的作用就是用来基础计算,跟小学课本一样,包含:加 +
,减 -
,乘 *
,除 /
,取余(也叫做取模) %
,指数 **
,自增 ++
,自减 --
。
只是需注意:乘号不再是 x
,除号也不再是 ÷
!
与我们学过的运算法则一样,乘法与除法优先级比加减法高,如果要改变优先级,需要使用括号 ()
,只是一个算式中有多个括号还是使用小括号,不用中括号
而已。
console.log(3 + 5);
console.log(3 + '5');
console.log(10 - 3);
console.log(2 * 4);
console.log(10 / 2);
console.log(10 % 3);
console.log(2 ** 3);
let a = 5;
console.log(a++);
console.log(++a);
console.log((2 + 3) * 4);
console.log(((2 + 3) - (5 -3)) * 4);
2、比较运算符
一般用于逻辑比较,比如比较两个值是否相等,比较两个数的大小等等。包含:等于 ==
,严格等于(全等于) ===
,不等于 !=
,严格不等于(不全等) !==
,大于 >
,小于 <
,大于等于 >=
,小于等于 <=
需特别注意:==
与 !=
会存在类型转换,所以 JS 建议使用 ===
与 !==
。
console.log(5 == '5');
console.log(0 == false);
console.log(5 != '5');
console.log(5 === '5');
console.log(0 === false);
console.log(5 !== '5');
console.log(3 > 2);
console.log('apple' > 'banana');
console.log(2 >= 2);
console.log(2 <= 2);
如果要比较值类型不同,建议显示转换类型再用 ===
比较。比如:
const a = 5;
const b = '5';
if (a + '' === '5') {}
if (b - 0 === 5) {}
3、逻辑运算符
用于逻辑判断,包含:逻辑与 &&
,逻辑或 ||
,逻辑非 !
。
需注意他们的短路特性。
console.log(true && 'Hello');
console.log(false && 'Hello');
console.log(0 || 'default');
console.log('A' || 'B');
console.log(!true);
console.log(!!'非空字符串');
function greet(name) {
name = name || 'Guest';
console.log(`Hello, ${name}!`);
}
greet();
true && console.log('执行了!');
false || console.log('执行了!');
4、赋值运算符
用于给变量赋值,包含:赋值(等于) =
,加等于(累加) +=
,减等于(累减) -=
,乘等于(累乘) *=
,除等于(累除) /=
,模等于(累模) %=
,幂等于(累幂) **=
。
let x = 10;
x += 5;
x *= 2;
x **= 2;
console.log(x);
5、位运算符
二进制的位运算符,据说是最快的运算符,当然一般编程用不上,如果您用 JS 进行大量的计算操作时,比如:图形图像算法、加密算法等相关操作,这时候就必须需掌握位运算了!包含:按位与 &
,按位或 |
,按位异或 ^
,按位非 ~
,左移 <<
,右移 >>
,无符号右移 >>>
。
这部分运算符涉及到底层的二进制运算,如果有兴趣可以查找相关资料学习。
console.log(5 & 3);
console.log(5 | 3);
console.log(-1 >>> 0);
6、三元运算符
又称为三目运算符(吐槽下:乱七八糟的名字特多),一般用于简化 if else
语句,但不建议过多嵌套,要不然代码阅读起来费劲。
语法:condition ? expr1 : expr2
。
const age = 20;
const canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote);
if (age >= 18) {
console.log('Yes');
} else {
console.log('No');
}
const a = age > 80 ? '高龄老人' : (age > 60 ? '老年人' : (age > 40 ? '中年人' : '年轻人'))
可以看看多次嵌套的代码是否是难以阅读,为了项目的可维护性,真心不建议把三元运算符用于多次嵌套。
7、特殊运算符
JS 内置的关键字,包含:typeof
, instanceof
, delete
, void
, in
, new
。
console.log(typeof 42);
console.log(typeof null);
class Person {}
const p = new Person();
console.log(p instanceof Person);
const obj = { a: 1 };
delete obj.a;
console.log(obj.a);
console.log(void (1 + 1));
console.log('toString' in obj);
function Car(brand) {
this.brand = brand;
}
const myCar = new Car('Tesla');
console.log(myCar.brand);
8、ES6+ 运算符
ES6 之后新增的一些运算符,骚操作从这里开始。包含:展开运算符 ...
, 可选链 ?.
, 空值合并 ??
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
console.log(...arr1);
console.log(arr2);
const user = { address: { city: 'Paris' } };
console.log(user?.address?.city);
console.log(user?.phone?.number);
const input = null;
const value = input ?? 'default';
类型转换规则
当操作数类型不同时,JS 会按内部规则尝试进行类型转换:
const obj = { toString: () => '100' };
console.log(obj > 50);
console.log(true > -1);
console.log(false < 1);
console.log(null > -1);
console.log(undefined > 0);
console.log('123' > 50);
console.log('abc' > 0);
const arr = [10];
console.log(arr > 5);
console.log('0x1f' > 30);
console.log('' > -1);
console.log(0 == '');
console.log(true == '1');
console.log(false == '0');
console.log([1] > 0);
console.log([] > -1);
console.log([] == 0);
console.log([] == false);
常见问题
1、== 和 === 的区别是什么?
答:== 会进行类型转换后比较,=== 严格比较值和类型。
2、逻辑运算符 && 和 || 的返回值是什么?
答:返回第一个决定表达式结果的子表达式值(短路求值)。
3、1 + '1' 和 '1' + 1 的结果是什么?
答:均为 '11'(字符串拼接)。
4、0 == false 和 '' == false 的结果是什么?为什么?
答:均为 true,因 == 会进行隐式转换。
5、typeof null 返回什么?为什么?
答:'object'(历史遗留问题)。
6、可选链 ?. 和空值合并 ?? 的作用是什么?
答:obj?.prop 避免访问 null/undefined,a ?? b 仅在 a 为 null/undefined 时返回 b。
7、以下代码的输出是什么?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
8、console.log(!!' ')
的输出是什么?
答:true(非空字符串转布尔值为 true)。
9、如何用短路求值简化代码?
const value = input || defaultValue;
10、如何安全访问嵌套对象属性?
答:使用可选链 obj?.a?.b ?? 'default'。
写在最后
优先使用 ===
和 !==
避免 JS 的隐式转换带来的不确定性。
隐式转换机制需特别注意,特别是在处理用户输入、API 接口响应数据时,稍不注意就掉坑了!!
如果您有大量计算工作量,那么必须啃书二进制的位运算符,否则使用十进制运算会拖慢程序运行速度。
转自https://www.cnblogs.com/linx/p/18896521
该文章在 2025/6/3 9:47:40 编辑过