文章内容
2021/5/13 18:22:38,作 者: 黄兵
Typescript push undefined
今天在写代码的时候出现了如下错误:
ERROR TypeError: Cannot read property 'push' of undefined
具体代码如下:
parentModel: IPCrawlerSupportModel[]; getAllParent(): void { this.supportService.getAllSupport().subscribe(res => { for (const item of res) { if (item.parent) { this.parentModel.push({parent: true, id: item.id, title: item.title}); } } }); }
出现问题的原因:
Array未初始化。
解决方案:
初始化Array:
parentModel: IPCrawlerSupportModel[] = []; getAllParent(): void { this.supportService.getAllSupport().subscribe(res => { for (const item of res) { if (item.parent) { this.parentModel.push({parent: true, id: item.id, title: item.title}); } } }); }
参考资料:
1、TypeScript: Cannot read property 'push' of undefined in [null]
黄兵个人博客原创。
评论列表