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

JavaScript使用for循环遍历数组筛选sedan对象push到新数组求助

filterCars函数问题排查与实现

原代码问题清单

  • 函数入参cars未被使用,内部硬编码了车辆数组,不符合通用函数设计要求
  • 属性读取逻辑错误:carArr.type是读取数组本身的type属性,该属性不存在,需读取当前遍历下标对应的元素属性carArr[i].type
  • 存在提前返回逻辑:return sedanCars.push("sedan")会导致第一次判断后就直接终止函数执行,且push方法返回的是数组新长度,不是数组本身
  • 推入数据不符合要求:要求推入符合条件的车辆对象,原代码推入的是字符串"sedan"
  • 函数末尾未返回最终筛选出的sedanCars数组
  • 存在多余的console.log语句,不符合题目要求

修正后代码

function filterCars (cars) {
  const sedanCars = []
  const arrayLength = cars.length
  for (var i = 0; i < arrayLength; i++) {
    const currentCar = cars[i]
    if(currentCar.type === "sedan") {
      sedanCars.push(currentCar)
    }
  }
  return sedanCars
}

调用验证

使用测试数据调用即可得到预期结果:

const testCars = [
  { type: 'sedan', color: 'white'},
  { type: 'truck', color: 'blue'},
  { type: 'sedan', color: 'red'},
  { type: 'coupe', color: 'red'}
]
filterCars(testCars) 
// 返回结果:[ { type: 'sedan', color: 'white' }, { type: 'sedan', color: 'red' } ]

内容的提问来源于stack exchange,提问作者Gab-Pifer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:54:02