Angular 5中TypeScript如何为所有lectures元素添加unlock_users键值对
问题分析与解决方案
错误根源
你遇到的index_s和index_l返回undefined的问题,核心原因是解构赋值的变量名与map返回的对象属性名不匹配。
看这段代码:
for (const {section, index_s} of this.data['sections'].map((item, index) => ({ item, index })))
你通过map返回的是包含item和index属性的对象,但解构时却用了section和index_s——这两个键在返回的对象里根本不存在,自然会得到undefined。内层循环的lecture和index_l也犯了同样的错误。
修正方案1:匹配解构变量名
把解构的变量名改成和map返回的属性一致,就能正常获取元素和索引了:
for (const { item: section, index: index_s } of this.data['sections'].map((item, index) => ({ item, index }))) { console.log(section); console.log(index_s); for (const { item: lecture, index: index_l } of section['lectures'].map((item, index) => ({ item, index }))) { console.log(lecture); this.data['sections'][index_s]['lectures'][index_l]['unlock_users'] = 0; } }
这里的item: section是属性重命名,把item解构后赋值给section变量,既保持了语义化,又匹配了返回的对象属性。
更简洁的方案2:使用forEach遍历
其实完全不需要map+for...of的组合,数组的forEach方法本身就支持获取当前元素的索引,代码会更简洁易读:
this.data['sections'].forEach((section, index_s) => { console.log(section); console.log(index_s); section['lectures'].forEach((lecture) => { console.log(lecture); // 直接修改引用对象即可,无需通过索引回查原数组 lecture['unlock_users'] = 0; }); });
这里lecture是数组元素的引用,直接修改它的属性会同步到原数组中,代码更高效。
TypeScript类型优化建议(可选)
为了避免类型错误、让代码更规范,你可以定义对应的接口约束数据结构:
interface Lecture { title: string; media: string; unlock_users?: number; } interface Section { title: string; achievements: string[]; lectures: Lecture[]; } interface CourseData { prerequisites: string[]; targets: string[]; sections: Section[]; } // 给this.data指定类型 this.data: CourseData = { /* 你的JSON数据 */ };
这样TypeScript会帮你检查属性名的正确性,避免拼写错误。
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

