什么?和 ??意思是 javascript

What does ?. and ?? mean in javascript

下面的代码是做什么的?。和 ??平均值

history.replace(loacation.state?.redirectPath ?? '/home')

1.可选链接 (?.)

来自MDN 表示

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

console.log(adventurer.dog?.name); // expected output: undefined

console.log(adventurer.dog.name); // Thow an error message like 
//`"message": "Uncaught TypeError: Cannot read property 'name' of undefined",`

2。无效合并运算符 (??)

来自MDN表示

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

==> 因此如果 loacation.state?.redirectPathnull or undefined,则值将是 '/home'