考虑这个例子:很好的方式,如果在JavaScript对象链是有效
if(this.plantService.plants[id])
{
if(this.plantService.plants[id].Name)
{
if(this.plantService.plants[id].Name[0])
return this.plantService.plants[id].Name[0].value;
else
return '';
}
else
return '';
}
return '';
我想知道,如果它能够简化我在做什么在这里。
我的目标是测试对象链this.plantService.plants[id].Name[0]
的有效性。
但是,如果我只测试if(this.plantService.plants[id].Name[0]) {...}
异常被抛出。
任何建议? :)
您可以使用'&&'op erator在你的如果是这样的:'if(this.plantService.plants [id] && this.plantService.plants [id] .Name && this.plantService.plants [id] .Name [0]){return this.plantService。植物[id] .Name [0] .value} else {return''}' –
请向我们展示抛出的异常。你只是说有,但那是什么? –
@SuperCoolHandsomeGelBoy这将是一个'TypeError',因为您试图访问'undefined'上的属性。 –