[英]JavaScript optional destructuring argument in function
我有這個 function 簽名
const foo = (arg, { opt1, opt2, opt3 }) => {
...
};
但我希望第二個參數是可選的,例如調用 function 之類的
foo("Hello");
但是,我得到
TypeError:無法解構“未定義”或“空”的屬性
opt1
。
因此,我很想通過更改 function 來解決此問題,例如:
const foo = (arg, options = {}) => {
const { opt1, opt2, opt3 } = options;
...
};
但是想知道是否有更多的內聯替代方案?
您可以分配一個默認的 object 並同時進行解構。
如果沒有第二個參數或undefined
,則所有三個解構屬性的結果都是undefined
的。
const foo = (arg, { opt1, opt2, opt3 } = {}) => {
...
};
您可以在聲明 function 時執行此操作{ opt1, opt2, opt3 } = {}
。
你可以做:-
const foo = (arg, { opt1, opt2, opt3 } = {}) => {
...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.