单问号(Optional Chain)、双问号(空值合并)已经出来很长时间了, 但是有时候在使用时, 仍然会犯迷糊, 在此记录一下.
可选链 Optional Chain
可选链(?.)允许读取位于链接对象链深处的属性值, 当引用的属性为空(null或undefined)或调用的函数不存在时, 返回undefined. 比如之前的obj.first && obj.first.name 繁琐写法就可以使用obj.first?.name替代(都返回undefined). 参见下面的例子:
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
空值合并??(Nullish coalescing operator )
**空值合并操作符(??)**是一个逻辑操作符, 当左侧的操作数为null或undefined时, 返回右侧的值.
与逻辑或操作符 (||), 逻辑或操作符在左侧操作数为假值('', undefined, null, false, NaN) 返回右侧. 参考下面的例子:
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
const foo1 = null || 'default string';
console.log(foo1);
// expected output: "default string"
const baz1 = 0 || 42;
console.log(baz1);
// expected output: 42