如何避免“无法读取未定义的属性”错误?
2022-08-30 02:20:20
在我的代码中,我处理一个数组,该数组具有一些条目,其中许多对象嵌套在彼此内,而有些则没有。它看起来像下面这样:
// 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);
}
我知道我可以说,但是在彼此嵌套了多达5或6个对象的情况下,这是非常乏味的。有没有其他(更简单的)方法,我可以让它只在它存在的情况下做,但不抛出错误?if(a.b){ console.log(a.b.c)}
console.log