2015-12-02 82 views
1

我很想知道检查子节点是否存在的最佳实践方法。检查javascript中是否存在子节点的最佳方法是什么?

var object = {} 

可以说,我想访问:object.child.element它将返回:

Uncaught TypeError: Cannot read property 'element' of undefined

因为child是不确定的。

我可以检查每个节点首先被定义:

if (object.child) { 
    object.child.element 
} 

所以这将避免TypeErrorobject.child应该undefined,但如果我们不得不说的5个元素,让所有这些if语句将不会是一个可行的解。

所以我倾向于做的是把这个地段包装在try

try { 
    var test = object.child.element.foo.bar; 
} catch (error) { 
    console.log(error); 
} 

so test只有存在child,element和foo节点时才会存在。

有没有比这更好的模式使用?

+0

我更喜欢前一种方法,并避免设计太多if语句来避免它。如果我需要'object.child.element.foo.bar',我会调用'object.getBar()'(它在内部检查一个空的'child'并返回'child.getBar()'或null,等等。)。 – Brian

回答

2

绝对不是在可读性方面的最佳实践,但我经常使用下面的结构(不只是为节点,但通常情况下):

if (object.child && object.child.element) 

见这里:

var a = {}; 
 
var b = {"child": {}}; 
 
var c = {"child": {"element": "finally"}}; 
 
      
 
console.log(a.child && a.child.element); 
 
console.log(b.child && b.child.element); 
 
console.log(c.child && c.child.element);

随着嵌套越多,代码越变得越糟糕,所以你最终可能会看到一些丑陋的东西:

object && object.child && object.child.element && object.child.element.another... 

但是,好事是,它的任务很好地工作,以及:

var obj = {"child": 123}; 
var other = obj && obj.child; // 123 
0

如果您知道属性字符串,可以递归地检查存在的名称。

var properties = ["child", "element", "foo", "bar"]; 
var i = 0; 
var test = obj; 
while(i < properties.length && !!test[properties[i]]) { 
    test = test[properties[i++]]; 
} 
if(i === properties.length) console.log("success", test); 
相关问题