考虑这个例子:
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 '';
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能简化我在这里做的事情.
我的目标是测试对象链this.plantService.plants[id].Name[0]的有效性.
但是,如果我只是测试if(this.plantService.plants[id].Name[0]) {...}异常被抛出.
有什么建议?:)
在检查值和类型后,您可以使用对象减少数组。
function getIn(object, keys, def) {
return keys.reduce(function (o, k) {
return o && typeof o === 'object' && k in o ? o[k] : def;
}, object);
}
var object = { plantService: { plants: [{ Name: [{ value: 42 }] }] } };
console.log(getIn(object, ['plantService', 'plants', 0, 'Name', 0, 'value'], 'default value'));
console.log(getIn(object, ['b', 'c', 'd', 'e'], 'default value'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |