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

TypeScript调用map函数报错:father.map is not a function问题排查

问题分析与解决

核心错误点

  1. 变量赋值逻辑错误
    你写的var father = parent;是把TypeScript的接口parent直接赋值给变量father,这完全不符合逻辑。正确的做法是将从JSON加载的单个parent类型的实例对象赋值给father,比如:
// 示例:解析JSON数据并赋值
const father: parent = JSON.parse(你的JSON数据字符串);
  1. 调用map的对象错误
    father是单个parent对象,不是数组,而map是数组专属方法,所以会抛出father.map is not a function的错误。你需要遍历的是father对象里的addresses属性——这才是address类型的数组,每个元素都包含street属性。

正确代码示例

export interface parent{
   fName: string;
   addresses: Array<address>;
}

export interface address{
   street: string;
   city: string;
   state: string;
   zip: string;
}

// 模拟从JSON加载的父对象数据
const father: parent = {
  fName: "Dan",
  addresses: [
    { street: "5th Avenue", city: "New York", state: "NY", zip: "10010" },
    { street: "Sunset Boulevard", city: "Los Angeles", state: "CA", zip: "90028" }
  ]
};

// 提取所有street属性组成数组
const streets = father.addresses.map(addr => addr.street);
console.log(streets); // 输出: ["5th Avenue", "Sunset Boulevard"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:30:47