Javascript 使用typescript(javascipt)映射对象
您好,我想根据这些创建一张地图,如果。。有没有办法创建映射并编写更好的代码Javascript 使用typescript(javascipt)映射对象,javascript,arrays,json,angular,typescript,Javascript,Arrays,Json,Angular,Typescript,您好,我想根据这些创建一张地图,如果。。有没有办法创建映射并编写更好的代码 findViewDetailPolicy(policy) { if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'STANDARD') { this.path = this.policyPathDetailStandard; this.router.navigate([this.pat
findViewDetailPolicy(policy) {
if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'STANDARD') {
this.path = this.policyPathDetailStandard;
this.router.navigate([this.path]);
}
if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'PACCHETTO') {
this.path = this.policyPathDetailModulare;
this.router.navigate([this.path]);
}
if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'SAVING') {
this.path = this.policyPathDetailSaving;
this.router.navigate([this.path]);
}
if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'CQ') {
this.path = this.policyPathDetailCq;
this.router.navigate([this.path]);
}
if (policy['displayInfo']['displayTypeDetail']['displayType'] === 'COLLETTIVA') {
this.path = this.policyPathDetailCollective;
this.router.navigate([this.path]);
}
}
地图可以是这样的:
const mapToPathProp = {
STANDARD: "policyPathDetailStandard",
PACCHETTO: "policyPathDetailModulare",
SAVING: "policyPathDetailSaving",
CQ: "policyPathDetailCq",
COLLETTIVA: "policyPathDetailCollective"
};
然后:
findViewDetailPolicy(policy) {
let pathProp = mapToPathProp[policy.displayInfo.displayTypeDetail.displayType];
if (pathProp) {
this.path = this[pathProp];
this.router.navigate([this.path]);
}
}
您的代码可以归结为:
findViewDetailPolicy(policy) {
const map = { STANDARD: this.policyPathDetailStandard, ... };
this.path = map[policy['displayInfo']['displayTypeDetail']['displayType']];
this.router.navigate([this.path]);
}
开关箱可以完成这项工作。检查文档。不是映射,而是更好的方法是尝试将
policy['displayInfo']['displayitypedetail']['displayType']
放入变量中,并以更好的方式编写这些条件const mapToPathProp={STANDARD:“policypathtailstandard”,PACCHETTO:“policypathtailmodulere”,SAVING:“policypathtailsaving”,CQ:“policypathtailcq”,COLLETTIVA:“policyPathDetailCollective”};在这个对象中。。用哪种方法传递objectI中path的属性我不明白你在问什么<例如,code>pathProp将是“polidyPathDetailStandard”,而this[pathProp]
将与您执行的this.polidyPathDetailStandard
一样。这说明了吗?此方法的优点是只创建一次映射,而不是每次调用函数时。此外,当与任何if
条件不匹配时,接受的答案的行为与您的代码不同。