解构函数参数时,如果函数参数未定义如何处理?
const product = {
label: 'Notebook',
price: 50
};
const destructSample = ({label, price}) => {
console.log(label, price);
}
destructSample(product);
destructSample(undefined);
destructSample(未定义);抛出以下错误
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)
如何解决这个问题? 谢谢。
最佳答案
一个default value
可以使用
const product = {
label: 'Notebook',
price: 50
};
const destructSample = ({label, price}= {}) => {
console.log(label, price);
}
destructSample(product);
destructSample(undefined);
注意:- 仅当没有传递参数或未定义作为参数传递时,默认参数才会出现,因此如果您想处理一些更虚假的值你可以做这样的事情
const product = {
label: 'Notebook',
price: 50
};
const destructSample = (obj) => {
let {label, price}= obj === undefined || obj === null ? {} : obj
console.log(label, price);
}
destructSample(product);
destructSample(undefined);
destructSample();
destructSample(null);
关于javascript - 如何处理 JavaScript 中未定义的函数参数的解构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889171/