今早项目刷新启动时, 报错undefined的问题, 刷新又没事了...复盘了一下, 应该是项目初始化的时候有某个值没有取到, 所以优化一下, 用到了??(空值合并操作符)以及?.(可选链操作符)。
主要用于避免出现空值时导致页面崩溃, 但是相反的, 也不容易排查问题了...所以, 逻辑复杂时酌情谨慎使用。
1. 空值合并操作符(??
)
只有当左侧为null和undefined时,才会返回右侧的数
空值合并操作符(??
)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 ||
来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,''
或 0
)时。见下面的例子。
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0 // 0( 0虽然是假值,但不是 null 或者 undefined)
const cvn = "" ?? 42;
console.log(cvn);
// expected output: "" // ""(空字符串虽然是假值,但不是 null 或者 undefined)
const fmx = null || 'default string';
console.log(fmx);
// expected output: "default string"
const mcm = 0 || '参考值'
console.log(mcm);
// expected output: '参考值' // (0是假值, 返回右侧值)
const cvn = "" || 42;
console.log(cvn);
// expected output: 42 //("" 空字符串是假值, 返回右侧值)
2. 可选链操作符( ?.
)
可选链操作符( ?.
)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?.
操作符的功能类似于 .
链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值
语法:obj?.prop obj?.[expr] arr?.[index] func?.(args)
示例:
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
1). 函数调用:
let result = someInterface.customMethod?.();
// 如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()
2). 可选链与表达式:
let nestedProp = obj?.['prop' + 'Name'];
3). 可选链访问数组:
let arrayItem = arr?.[42];
4). map中:
let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});
let nameBar = myMap.get("bar")?.name;
// 在一个不含 bar 成员的 Map 中查找 bar 成员的 name 属性,因此结果是 undefined。
5). 短路计算:
let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];
console.log(x); // x 将不会被递增,依旧输出 0
// 当在表达式中使用可选链时,如果左操作数是 null 或 undefined,表达式将不会被计算
6). 连用可选链操作:
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // details 的 address 属性未有定义
}
};
let customerCity = customer.details?.address?.city;
// … 可选链也可以和函数调用一起使用
let duration = vacations.trip?.getTime?.();
7). 与空值合并操作符一起使用
空值合并操作符可以在使用可选链时设置一个默认值:
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”