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

订阅回调中数组map操作返回undefined的问题解决

问题解决:map返回全undefined数组的原因及修复

问题场景

我有一个从后端(BE)获取数据的方法,代码如下:

getChartsData(): any {
const documentStyle = getComputedStyle(document.documentElement);
const textColor = documentStyle.getPropertyValue('--text-color');
const textColorSecondary = documentStyle.getPropertyValue(
  '--text-color-secondary'
);
const surfaceBorder = documentStyle.getPropertyValue('--surface-border');

this._testFileService.getFileData().subscribe((result) => {
  console.log(result);
  console.log(
    result.map((obj: any) => {
      obj.city;
    })
);

问题:console.log(result)返回包含369个对象的数组,但console.log( result.map((obj: any) => { obj.city; }) )返回全undefined的数组,请问该如何解决?


问题原因

你在map的回调函数里只是访问了obj.city,但没有返回这个值。箭头函数如果用大括号包裹代码块,必须显式使用return语句才能返回结果,否则默认返回undefined。

修复方法

有两种简洁的修复方式:

  1. 显式添加return语句:
console.log(
  result.map((obj: any) => {
    return obj.city; // 显式返回city属性
  })
);
  1. 使用箭头函数的隐式返回:
    如果回调逻辑只有一行返回操作,可以省略大括号,此时箭头函数会自动返回表达式的结果:
console.log(
  result.map((obj: any) => obj.city) // 隐式返回city属性
);

额外验证(可选)

如果修复后仍返回undefined,请确认:

  • 数组中的对象确实包含city属性(可通过console.log(result[0])查看第一个对象的结构)
  • 属性名拼写无误(比如是否是City/cityName而非city)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:43:11