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

JavaScript对象数组提取键值问题:gatherPets函数返回结果格式不符的解决方案求助

解决gatherPets函数的数组拼接问题

嗨,我来帮你搞定这个问题!你的代码现在有两个关键问题,导致返回结果不符合预期:


问题1:循环边界错误

你写的循环条件是for (let i=0; i <=people.length; i++ ),但数组的索引是从0开始的,people.length是数组的元素总数。比如你的输入数组有2个元素,索引仅为0和1,当i等于2的时候,people[2]是undefined,访问它的pets属性会直接报错(虽然你的示例结果里没体现,但这是个隐藏bug)。正确的条件应该是i < people.length,这样循环只会遍历到最后一个有效的索引。

问题2:数组拼接方式错误

你用newArray = newArray + people[i].pets来合并数组,但数组和数组相加会被强制转换成字符串拼接。比如['Bear', 'Minu'] + ['Basil', 'Hamish']会变成字符串"Bear,MinuBasil,Hamish",这就是你看到奇怪结果的核心原因。

要正确合并数组,你可以用这几种方式:

方式1:使用Array.concat()

这个方法会返回一个新数组,把原数组和传入的数组合并:

function gatherPets(people) {
  let newArray = [];
  for (let i = 0; i < people.length; i++) {
    newArray = newArray.concat(people[i].pets);
  }
  return newArray;
}

方式2:使用Array.push()展开数组

用展开运算符...把pets数组的元素逐个添加到newArray里,效率更高:

function gatherPets(people) {
  let newArray = [];
  for (let i = 0; i < people.length; i++) {
    newArray.push(...people[i].pets);
  }
  return newArray;
}

更简洁的写法:用Array.flatMap()

如果你想让代码更精简,可以用ES6的flatMap方法,一步完成遍历和扁平化:

function gatherPets(people) {
  return people.flatMap(person => person.pets);
}

调用你提供的测试代码:

gatherPets([
  { name: 'Malcolm', pets: ['Bear', 'Minu'] },
  { name: 'Caroline', pets: ['Basil', 'Hamish'] },
]);

现在会正确返回['Bear', 'Minu', 'Basil', 'Hamish']啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:49:07