TypeScript按指定位置排序数组并匹配组件ID求助
解决方案
问题分析
现有代码的核心问题:
- 仅打印匹配结果,未将结果收集为目标数组
- 使用
!强制断言存在匹配项,存在运行时报错风险 forms中["en-HK" || "en-MO"]的键名写法错误,逻辑或运算后实际键为"en-HK",无法同时匹配en-MO
修正后的代码
// 修复forms键名问题:多locale对应同一份配置需单独声明 const forms: FormsToLocale = { ja: [ { componentId: "email", position: 1 }, { componentId: "title", position: 2 }, { componentId: "japanName", position: 3 }, { componentId: "phoneNumber", position: 4 }, ], "en-HK": [ { componentId: "email", position: 1 }, { componentId: "verificationCode", position: 2 }, { componentId: "title", position: 3 }, { componentId: "firstName", position: 4 }, { componentId: "lastName", position: 5 }, ], "en-MO": [ { componentId: "email", position: 1 }, { componentId: "verificationCode", position: 2 }, { componentId: "title", position: 3 }, { componentId: "firstName", position: 4 }, { componentId: "lastName", position: 5 }, ], default: [ { componentId: "email", position: 1 }, { componentId: "title", position: 2 }, { componentId: "firstName", position: 3 }, { componentId: "lastName", position: 4 }, { componentId: "phoneNumber", position: 5 }, ], }; const componentsFormMapping: ComponentFormMapping[] = [ { componentId: "email", component: "EmailLightAccountComponent" }, { componentId: "title", component: "TitleLightAccountComponent" }, { componentId: "firstName", component: "FirstnameLightAccountComponent" }, { componentId: "lastName", component: "LastnameLightAccountComponent" }, { componentId: "japanName", component: "JapanNameLightAccountComponent" }, { componentId: "phoneNumber", component: "PhoneLightAccountComponent" }, { componentId: "verificationCode", component: "SendCodeComponent" }, ]; // 转成Map提升查找效率,避免每次遍历数组 const componentMap = new Map(componentsFormMapping.map(item => [item.componentId, item.component])); const createForm = (locale: string = "default") => { // 获取对应locale配置,找不到则用default const formConfig = forms[locale as keyof typeof forms] || forms.default; // 按position排序后映射为组件名数组,过滤无效项 return formConfig .sort((a, b) => a.position - b.position) .map(item => componentMap.get(item.componentId)) .filter(Boolean) as string[]; }; // 测试日语表单 const japanFormResult = createForm("ja"); console.log(japanFormResult); // 输出:["EmailLightAccountComponent", "TitleLightAccountComponent", "JapanNameLightAccountComponent", "PhoneLightAccountComponent"]
关键优化点
- 将组件映射转为
Map,查找复杂度从O(n)降为O(1),提升性能 - 增加locale参数支持,自动 fallback 到默认配置
- 显式按
position排序,确保输出顺序符合要求 - 过滤找不到匹配项的结果,避免数组出现
undefined - 修复
forms键名错误,支持多locale独立配置
内容的提问来源于stack exchange,提问作者Younes
相关产品推荐
相关产品推荐

