可选链操作符的定义
可选链操作符(?.)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空([nullish]) ([null] 或者 [undefined] 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
基本用法
🌰
let allName = {
name: "zz",
age: {
name: "cat"
}
}
console.log(allName.genter ?. age)
// undefined
🌰🌰
let nestedProp = obj.first?.second;
这句代码等价于
let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
🌰🌰🌰
const zz = {
a: 'foo',
b: {
c: 'bar'
}
}
console.log(zz.b?.c) // 输出 bar
console.log(zz.d?.c) // 输出 undefined
console.log(zz.func?.()) // 不报错,输出 undefine
可选链除了可以用在获取对象的属性,还可以用在数组的索引
arr?.[index],也可以用在函数的判断func?.(args),当尝试调用一个可能不存在的方法时也可以使用可选链。
调用一个对象上可能不存在的方法时(版本原因或者当前用户的设备不支持该功能的场景下),使用可选链可以使得表达式在函数不存在时返回 undefined 而不是直接抛异常
应用场景
🌰 以前的用法 我相信很多人在项目中都会用这种用法来避免js出错
let allName = {
name: "zz",
age: {
name: "cat"
}
}
if(allName && allName.age && allName.age.name === "cat") {
}
现在我们学会了可选链操作符,我们来试试
if(allName ?. age ?. name === "cat") {
}
🌰🌰 我们使用空值合并操作符设置一个默认值,什么是空值合并操作符,可以阅读这篇文章,空值合并操作符。
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "zz";
console.log(customerCity); // “zz”
js中的空值合并操作符(??)
定义
空值合并操作符
??是一个逻辑操作符,当左侧的操作数为null或者undefined时,返回其右侧操作数,否则返回左侧操作数。
基本用法
const foo = null ?? "string"
// string
const foo = "zz" ?? "string"
// zz
const foo = undefined ?? "string"
// string
我们从以上是三个案例可以总结出来 当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数
我的疑问
空值合并操作符(??)和逻辑或操作符(||)有什么不一样呢,可能大家在项目中经常用到逻辑或操作符号(||),那我们在来比较下他们的区别吧
js中的逻辑或操作符(||)
逻辑操作符
||,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。
基本用法
const foo = null || "string"
// string
const foo = undefined || "string"
// string
cosnt foo = 0 || "string"
// string
cosnt foo = 0 || "string"
// string
const foo = "" || "string"
// string
经过我们比较会发现,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时候。
业务场景
- 我们在开发中与后端联调都会发现这样一个问题。明明后端应该返回数组,却因为某种原因返回的null。这个时候我们用空值合并操作符可以避免带来的一些问题。
- 业务中做一些判断,如下
if(value ?? '' !== '')
[不能与 AND 或 OR 操作符共用]
将 ?? 直接与 AND(&&)和 OR(||)操作符组合使用是不可取的。(译者注:应当是因为空值合并操作符和其他逻辑操作符之间的运算优先级/运算顺序是未定义的)这种情况下会抛出 SyntaxError 。
null || undefined ?? "foo"; // 抛出 SyntaxError
true || undefined ?? "foo"; // 抛出 SyntaxError
但是,如果使用括号来显式表明运算优先级,是没有问题的:
(null || undefined ) ?? "foo"; // 返回 "foo"