订阅回调中数组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。
修复方法
有两种简洁的修复方式:
- 显式添加return语句:
console.log( result.map((obj: any) => { return obj.city; // 显式返回city属性 }) );
- 使用箭头函数的隐式返回:
如果回调逻辑只有一行返回操作,可以省略大括号,此时箭头函数会自动返回表达式的结果:
console.log( result.map((obj: any) => obj.city) // 隐式返回city属性 );
额外验证(可选)
如果修复后仍返回undefined,请确认:
- 数组中的对象确实包含
city属性(可通过console.log(result[0])查看第一个对象的结构) - 属性名拼写无误(比如是否是
City/cityName而非city)
内容的提问来源于stack exchange,提问作者Eugene Sukh
相关产品推荐
相关产品推荐

