在我的代码中,我处理一个数组,该数组有一些条目,其中有许多对象嵌套在另一个对象中,而有些对象没有嵌套。它看起来像下面这样:
// where this array is hundreds of entries long, with a mix
// of the two examples given
var 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,如果它存在,但没有抛出一个错误?