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

如何在通过索引修改值时将Angular模型推入数组?

问题描述

在Angular中使用TierModel模型创建重复字段,尝试将模型实例推入数组时触发未定义错误,错误源于对单个模型实例错误地使用索引操作。

模型代码

export class TierModel {
    feeName: string;
    feeDescription: string;
    unit: string;
    tierStart: number;
    tierEnd: number;
    rate: number;
};

报错的推入数组代码

addForm()
{
    const obj = new TierModel()

    obj[0].feeName = 'test';
    obj[0].unit = 0;
    
    this.dataarray.push(obj);
}
解决方案

错误原因

new TierModel()创建的是单个TierModel对象,并非数组,因此obj[0]会返回undefined,对undefined赋值自然触发错误。

正确写法

场景1:创建单个对象修改后推入数组

直接操作单个对象的属性,无需使用索引:

addForm() {
  const obj = new TierModel();
  obj.feeName = 'test';
  obj.unit = '0'; // 注意模型中unit是string类型,需传入字符串
  this.dataarray.push(obj);
}

场景2:通过索引操作对象(匹配你的需求)

如果一定要用索引操作,可先创建包含模型实例的数组,再通过索引修改属性,最后推入目标数组:

addForm() {
  // 创建包含单个TierModel实例的数组
  const tierList = [new TierModel()];
  // 通过索引修改数组内的对象属性
  tierList[0].feeName = 'test';
  tierList[0].unit = '0';
  // 将数组元素推入目标数组
  this.dataarray.push(...tierList);
}

也可以直接操作目标数组的元素,用索引修改刚推入的对象:

addForm() {
  // 先推入空实例
  this.dataarray.push(new TierModel());
  // 获取刚推入元素的索引
  const lastIndex = this.dataarray.length - 1;
  // 通过索引修改属性
  this.dataarray[lastIndex].feeName = 'test';
  this.dataarray[lastIndex].unit = '0';
}

注意事项

模型中unit字段的类型是string,赋值时要传入字符串(比如'0'),不要直接传数字0,避免类型不匹配问题。

内容的提问来源于stack exchange,提问作者saurav.rox

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:55:36