Article directory
1. Question 1:
http://www.codebaoku.com/question/question-sd-1010000042870944.html
//1、npm安装
npm install @babel/plugin-proposal-optional-chaining // 可选链运算符 ?.
npm install @babel/plugin-proposal-nullish-coalescing-operator // 空值合并运算符 ??
//2、配置babel.config.js
module.exports = {
plugins: [
'@babel/plugin-proposal-optional-chaining', // 可选链运算符 ?.
'@babel/plugin-proposal-nullish-coalescing-operator' // 空值合并运算符 ??
]
}
2. Question 2:
3. Use:
[1] Null coalescing operator (??)
A logical operator that
null 或者 undefined
returns its右侧
operand when the left operand is , otherwise returns the left operand.
Note: Unlike the logical OR operator (||), the logical OR operator returns the right operand if the left operand is false. That said, if you use || to set default values for certain variables, you may encounter unexpected behavior. Such as when false (for example, '' or 0).
const foo = null ?? 'default string';
console.log(foo); // "default string"
const baz = 0 ?? 42;
console.log(baz); // 0
const baz = 0 || 42;
console.log(baz); // 42
[2] Optional chain operator (?.)
Allows reading the value of properties located deep in a chain of connection objects without having to explicitly verify that each reference in the chain is valid. The function of the ?. operator is similar to that of the . chaining operator, except that it does not cause an error if the reference is null (null or undefined), and the short-circuit return value of this expression is undefined. When used with a function call, returns undefined if the given function does not exist.
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName); //undefined
console.log(adventurer.someNonExistentMethod?.()); // undefined
console.log(adventurer.someNonExistentMethod.());
// Error: Unexpected token .'('