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

TypeScript中无法为数组内对象设置动态ID的技术问题

动态ID以对象数组存储的类型错误解决方法

问题说明

需求是将动态ID以对象数组格式存储,期望格式如下:

[
  {
    id: 250,
    how_many_times: 1
  },
  {
    id: 650,
    how_many_times: 2
  },
  {
    id: 850,
    how_many_times: 1
  }
]

但执行代码时出现错误:Property 'id' does not exist on type '{ id: string; }[]',用户编写的代码如下:

初始化数组:

popUpShowData = [
    {
      id : '',
      how_many_times: 0
    }
];

设置值的函数:

getPopup(dynamicId) {
   this.popUpShowData.id = dynamicId;
   this.popUpShowData.how_many_times = 1;
}

错误原因

popUpShowData是数组类型,不是单个对象,直接通过this.popUpShowData.id访问属性是错误的——数组本身没有id或how_many_times属性,这些属性属于数组内部的每个对象元素。

另外初始数组里的id设为空字符串,而需求中ID是数字类型,类型不匹配也会导致TypeScript报错。

解决方案

根据需求(记录每个ID的出现次数),正确逻辑是:检查数组中是否已存在当前dynamicId的对象,存在则累加次数,不存在则新增对象。

步骤1:正确初始化数组

如果是TypeScript,建议先定义类型并初始化空数组:

interface PopUpItem {
  id: number;
  how_many_times: number;
}

popUpShowData: PopUpItem[] = [];

如果是JavaScript,直接初始化空数组即可:

popUpShowData = [];

步骤2:编写正确的getPopup函数

getPopup(dynamicId: number) {
  // 查找数组中是否已有该ID的对象
  const existingItem = this.popUpShowData.find(item => item.id === dynamicId);
  
  if (existingItem) {
    // 已存在,次数加1
    existingItem.how_many_times += 1;
  } else {
    // 不存在,新增对象
    this.popUpShowData.push({
      id: dynamicId,
      how_many_times: 1
    });
  }
}

调用示例

当依次传入250、650、650、850时,popUpShowData会变成:

[
  { id: 250, how_many_times: 1 },
  { id: 650, how_many_times: 2 },
  { id: 850, how_many_times: 1 }
]

完全符合需求格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:15:41