在解构函数参数时,如果函数参数未定义,该如何处理?
const product = {
label: 'Notebook',
price: 50
};
const destructSample = ({label, price}) => {
console.log(label, price);
}
destructSample(product);
destructSample(undefined);
Run Code Online (Sandbox Code Playgroud)
destructSample(undefined); 引发以下错误
const destructSample = ({label, price}) => {
^
TypeError: Cannot destructure property `label` of 'undefined' or 'null'.
at destructSample (E:\PlayGround\NodeJs\nodeCourse\playground\destructuringError.js:6:24)
at Object.<anonymous> (E:\PlayGround\NodeJs\nodeCourse\playground\destructuringError.js:11:1)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Run Code Online (Sandbox Code Playgroud)
如何解决呢?谢谢。