You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular使用*ngFor遍历二维数组报读取undefined属性0错误

报错原因

*ngFor迭代语法的取值逻辑写错了。
当你写*ngFor="let done of this.launch.doneAreas; index as i"时,遍历过程中done代表的是doneAreas里的每一个子数组(也就是你push进去的每一组coords),i是当前子数组在外层数组的索引。
你模板里写的done[i][0]属于错误叠加索引:

  • 单组coords子数组长度固定为2,仅存在索引0、1两个元素
  • 当外层循环的i大于等于2时,在子数组上取索引i会得到undefined,再尝试读取undefined的0属性,就会触发TypeError: Cannot read properties of undefined (reading '0')报错。
修复方案

注:你服务层的二维数组定义、push存入coords的逻辑没有问题,不需要调整。

不需要在done上额外加[i]索引,直接通过done访问当前子数组的0、1位元素即可,修正后的模板代码:

<ng-container
  *ngFor="let done of this.launch.doneAreas; index as i">
  <div class="display-result">
    Case n° {{ i + 1 }} => ({{ done[0] }},{{ done[1] }})
  </div>
</ng-container>

按照你提供的数组结构,修复后页面会正确渲染如下结果:

  • Case n° 1 => (3,3)
  • Case n° 2 => (3,4)
  • Case n° 3 => (4,4)
  • Case n° 4 => (4,3)

内容的提问来源于stack exchange,提问作者MaxM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 21:24:20