JavaScript 中 Cannot destructure Property of Undefined 错误
当我们尝试从等于未定义的值中解构属性时,会发生“Cannot destructure Property of Undefined”错误。 要解决错误,请在解构属性时提供回退,例如 const {name} = undefined || {};。
下面是产生上述错误的示例代码
// ⛔️ Cannot destructure property 'name' of undefined
// as it is undefined
const {name} = undefined;
function test(obj) {
// ⛔️ Cannot destructure property 'country'
// of undefined, as it is undefined
const {country} = obj;
}
test();
我们试图从导致错误的未定义值中解构属性。
要解决该错误,请在解构时提供空对象的回退,或者如果使用函数,则为参数设置默认值。
const {name} = undefined || {};
console.log(name); // ?️ undefined
function test(obj = {}) {
const {country} = obj;
console.log(country); // ?️ undefined
}
test();
test(undefined);
我们使用了逻辑或 || 运算符。 如果左边的值是假的(例如 undefined),运算符返回右边的值。
如果上述六个值中的任何一个位于逻辑或 || 运算符的左侧,我们将返回一个空对象。
const {name} = undefined || {};
console.log(name); // ?️ undefined
这有助于我们避免“Cannot destructure Property of Undefined”错误。
我们在第二个例子中定义了一个带有默认参数的函数。
function test(obj = {}) {
const {country} = obj;
console.log(country); // ?️ undefined
}
test();
test(undefined);
或者,我们可以使用可选的链接运算符 ?.,如果引用未定义或为空,它会短路而不是抛出错误。
const fromDb = undefined;
const name = fromDb?.name;
console.log(name); // ?️ undefined
const obj = {name: 'Tom'};
const n = obj?.name;
console.log(n); // ?️ "Tom"
fromDb 变量存储一个未定义的值,所以我们短路返回未定义而不是抛出错误。
如果引用不是空值,则运算符返回相应的值。
我们可以使用可选的链接运算符来访问深层嵌套的属性。
const fromDb = undefined;
const floor = fromDb?.country?.address?.floor;
console.log(floor); // ?️ undefined
这种方法帮助我们避免在引用为空(null 或 undefined)时出现错误。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。