1.运算符
1.指数运算符
指数运算符**,可以计算乘方。2**3等同于Math.pow(2,3)
——来自es7
2.扩展运算符
虽然扩展运算符在es6中就已经存在了,但是只能给函数使用,在es9中为对象也提供了这样的机制。
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, ...obj1 }; // 将obj1的所有属性“剩余”地合并到obj2中
console.log(obj2); // { c: 3, a: 1, b: 2 }
function mergeObjects(base, ...rest) { // base:1 rest:2,3
let result = { ...base }; //a:1
for (const obj of rest) {
result = { ...result, ...obj }; //a:1,b:2 第二轮 a:1,b:2,c:3
}
return result;
}
const baseObj = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };
const mergedObj = mergeObjects(baseObj, obj2, obj3);
console.log(mergedObj); // { a: 1, b: 2, c: 3 }
——es9
3.可选链操作符
可以先判断对象是否有这个属性再使用
const user = {
id: 1,
profile: {
name: "John Doe",
contact: {
email: "john.doe@example.com"
}
}
};
// 传统方式,需要多次检查
let email = user && user.profile && user.profile.contact && user.profile.contact.email;
// 使用可选链操作符
let emailWithOptionalChaining = user?.profile?.contact?.email;
console.log(emailWithOptionalChaining); // 输出: "john.doe@example.com"
// 如果user是undefined
let noUser = undefined;
console.log(noUser?.profile?.contact?.email); // 输出: undefined,而不是抛出错误
4.逻辑赋值操作符
1. 使用逻辑或(||
)进行赋值
逻辑或操作符||
常用于为变量提供一个默认值,如果变量当前为falsey
(如null
、undefined
、0
、""
、NaN
、false
等),则将其设置为默认值。
let a = null;
a = a || 'default value';
console.log(a); // 输出: 'default value'
2. 使用空值合并操作符(??
)进行赋值
空值合并操作符??
用于为null
或undefined
的变量提供一个默认值。这与逻辑或