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
),运算符返回右边的值。
JavaScript 中的假值是:
null
、undefined
、0
、false
、""
(空字符串)、NaN
(不是数字)。
如果上述六个值中的任何一个位于逻辑或 ||
运算符的左侧,我们将返回一个空对象。
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);
如果未提供参数,或者在调用函数时提供了
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
)时出现错误。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。