如何避免'无法读取未定义的属性'错误?
在我的代码中,我处理的数组中有一些条目,其中有许多对象彼此嵌套,而有些则没有。它看起来像下面这样:
// where this array is hundreds of entries long, with a mix// of the two examples givenvar test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
这给了我一些问题,因为我需要有时遍历数组,并且不一致会给我带来如下错误:
for (i=0; i<test.length; i++) { // ok on i==0, but 'cannot read property of undefined' on i==1 console.log(a.b.c);}
我知道我可以说if(a.b){ console.log(a.b.c)}
,但是在最多有5个或6个对象相互嵌套的情况下,这是非常繁琐的。有没有其他(更简单)的方法,我只能执行console.log,如果它存在,但没有抛出错误?
森栏
四季花海
相关分类