【发布时间】:2020-02-19 20:23:44
【问题描述】:
我有一个函数,其目的是显示嵌套在数组中的特定对象的特定描述。这个想法是,一旦函数 (findSettings()) 接收到特定的数组 (systemSettings) 和某个键 (tab12)对象,它应该贯穿 switch 语句并提供其匹配的描述。
换句话说,如果函数的参数是“tab12”,那么它应该返回描述“tab12 的描述”。
我尝试使用 find 方法找到匹配的对象,效果很好,但如果我尝试运行 switch 语句,它会返回错误:'Obejct is possible undefined'。
const systemSettings = [
{key: 'tab1', value: 'Main Tab'},
{key: 'tab12', value: 'Tab 12'},
{key: 'tab13', value: 'Tab 13'},
{key: 'tab4', value: 'Tab 4'}
]
type sampObj = {
key: string;
value: string;
}
let info: string = '';
function findSetting(arr: sampObj[], settingKey: string) {
const selectedObjs = arr.find(obj => obj.key === settingKey);
switch(selectedObjs.key) {
case 'tab1':
info += 'Description for tab1';
break;
case 'tab12':
info += 'Description for tab12';
break;
case 'tab13':
info += 'Description for tab13';
break;
case 'tab4':
info += 'Description for tab4';
break;
default:
info += 'No description available'
}
}
findSetting(systemSettings, 'tab12')```
Any assistance would be highly appreciated.
Thanks.
【问题讨论】:
标签: javascript arrays typescript object switch-statement