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

JavaScript函数映射动物数组返回undefined问题求助

问题排查与修复:动物描述函数返回undefined的原因

你的问题出在map回调函数的属性引用上:你错误地使用了全局的animals数组来访问name/type/age属性,但animals是整个数组对象,它本身并没有这些属性,所以每个位置都会返回undefined。

正确的做法是使用map回调参数里的单个动物对象(你写的object可以改成更语义化的animal)来访问属性。

修复后的代码:

const sentence = (array) => {
  return array.map((animal) => {
    return `The ${animal.name} is a ${animal.type} and it is ${animal.age} years old.`
  })
}

如果想简化箭头函数写法,可以省略外层的大括号和return:

const sentence = (array) => 
  array.map(animal => 
    `The ${animal.name} is a ${animal.type} and it is ${animal.age} years old.`
  )

现在调用console.log(sentence(animals))就能得到正确的结果:

[
  "The Waffles is a dog and it is 7 years old.",
  "The Fluffy is a cat and it is 14 years old.",
  "The Spelunky is a dog and it is 4 years old.",
  "The Hank is a cat and it is 11 years old."
]

内容的提问来源于stack exchange,提问作者S.Y.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:05:18