有没有更简洁的方法来检查是否存在深层嵌套节点?
Is there a cleaner way to check if a deep nested node exists?
使用纯 javascript -- 无第三方/lodash 等
如果用户正在寻找深层嵌套节点的存在,是否有更简洁的方法来确保每个父节点都存在,以免 return 未定义?
为简单起见,在执行操作之前检查嵌套道具是否有长度。
问题是,尤其是在传递 props 时,在任何给定节点,您最终可能会得到 undefined
。
有没有办法避免像这样检查每个节点是否存在:
if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
// do something
}
类似这样的内容:
(我知道这是不正确的,因为任何节点都在 undefined
处理这个过程)。
if(!!Grandparent.Parent.child.prop3.length) {
// do something
}
// OR
if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
// do something
}
EX:
Grandparent: {
Parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
item: {
name: 'first',
type: 'string'
},
item: {
name: 'second',
type: 'number'
}
]
}
}
}
正如评论者所指出的,现代 JavaScript 提供了 optional chaining operator (?.
),您可以像这样使用它(只要您还没有尝试支持 IE):
const
grandparent = getObject(),
itemsCount = grandparent?.parent?.child?.prop3?.length,
oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");
function getObject(){
return {
parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
{ item: { name: 'first', type: 'string' }},
{ item: { name: 'second', type: 'number' }}
]
}
}
};
}
使用纯 javascript -- 无第三方/lodash 等
如果用户正在寻找深层嵌套节点的存在,是否有更简洁的方法来确保每个父节点都存在,以免 return 未定义?
为简单起见,在执行操作之前检查嵌套道具是否有长度。
问题是,尤其是在传递 props 时,在任何给定节点,您最终可能会得到 undefined
。
有没有办法避免像这样检查每个节点是否存在:
if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
// do something
}
类似这样的内容:
(我知道这是不正确的,因为任何节点都在 undefined
处理这个过程)。
if(!!Grandparent.Parent.child.prop3.length) {
// do something
}
// OR
if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
// do something
}
EX:
Grandparent: {
Parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
item: {
name: 'first',
type: 'string'
},
item: {
name: 'second',
type: 'number'
}
]
}
}
}
正如评论者所指出的,现代 JavaScript 提供了 optional chaining operator (?.
),您可以像这样使用它(只要您还没有尝试支持 IE):
const
grandparent = getObject(),
itemsCount = grandparent?.parent?.child?.prop3?.length,
oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");
function getObject(){
return {
parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
{ item: { name: 'first', type: 'string' }},
{ item: { name: 'second', type: 'number' }}
]
}
}
};
}