JavaScript 函数中的可选解构参数

JavaScript optional destructuring argument in function

我有这个函数签名

const foo = (arg, { opt1, opt2, opt3 }) => {
   ...
};

但我希望第二个参数是可选的,例如调用函数

foo("Hello");

但是,我得到

TypeError: Cannot destructure property opt1 of 'undefined' or 'null'.

因此,我很想通过更改函数来解决此问题,例如:

const foo = (arg, options = {}) => {
   const { opt1, opt2, opt3 } = options;

   ...
};

但想知道是否有更多的内联替代方案?

您可以分配默认对象并同时进行解构。

如果没有第二个参数或undefined.

,所有三个解构属性的结果都是undefined
const foo = (arg, { opt1, opt2, opt3 } = {}) => {
   ...
};

你可以这样做:-

const foo = (arg, { opt1, opt2, opt3 } = {}) => {

   ...
};

您可以在声明函数时{ opt1, opt2, opt3 } = {}这样做。