检查对象是否在 JavaScript 中具有嵌套属性
使用可选的链接运算符检查对象是否具有嵌套属性。
可选的链接运算符允许我们读取嵌套属性的值而不会在对象上不存在该属性时抛出错误,例如 obj?.a?.b
。
const obj = {a: {b: 'hello'}};
const value = obj?.a?.b;
console.log(value); // 👉️ hello
if (value !== undefined) {
// if this block runs
// 👉️ property exists on the object
}
我们使用可选的链接运算符来检查对象上是否存在嵌套属性。
使用可选的链接
?.
运算符类似于使用.
(点)表示法访问对象的属性,但是,当嵌套属性不存在时?.
运算符不会抛出错误。
相反,如果对象的属性不存在可选链接 ?.
运算符返回 undefined。
const obj = {};
const value = obj?.a?.b?.c;
console.log(value); // 👉️ undefined
if (value !== undefined) {
// if this block runs
// 👉️ property exists on the object
}
我们用了 ?.
运算符访问对象上不存在的嵌套属性。
当 ?.
运算符试图访问对象的 a 属性,它返回一个 undefined 值,并且短路也返回 undefined。
如果要省略 ?.
运算符,只需使用 .
(点)符号,你会得到一个错误 - “Cannot read property b of undefined”。
或者,我们可以使用逻辑 AND 运算符。
使用逻辑与 (&&) 运算符检查对象是否具有嵌套属性
检查对象是否具有嵌套属性:
-
使用点表示法访问第一个属性并检查它是否不等于
undefined
。 - 使用逻辑 AND 运算符链接另一个条件。
-
访问嵌套属性并检查它是否不等于
undefined
。
const obj = {};
if (obj.a !== undefined && obj.a.b !== undefined && obj.a.b.c !== undefined) {
// if this block runs
// 👉️ the a.b.c property exists on the object
}
我们手动检查嵌套属性是否存在。
我们使用了逻辑 AND &&
运算符,因此 if 语句中的条件将从左到右逐一检查。
如果任何条件的计算结果为假值,则 if 块将不会运行。
在上面的示例中,我们明确检查每个属性是否等于 undefined。 我们可能会在网上看到仅使用
&&
运算符的示例,但是,这种方法很容易出错。
以下示例检查对象属性的值是否为真。
JavaScript 中的真值都是非假值。 Falsy 值为:false、0、""、null、undefined、NaN。
不要写这样的代码:
const obj = {a: {b: {c: 0}}};
if (obj && obj.a && obj.a.b && obj.a.b.c) {
// 👉️ This never runs
// even though the `c` property exists
}
我们检查对象的属性是否为真,这不足以让我们确定该属性是否存在于对象上。
a.b.c 属性设置为 0,这是一个虚假值,因此即使属性 a.b.c 存在于对象上,if 块也不会运行,因为条件不满足。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。