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

如何用grades数组过滤courses数组,实现及格课程筛选

正确实现及格课程筛选函数

你之前的错误确实是因为filter回调的第一个参数是数组元素(即课程名称),而非索引,所以grades[x]本质是尝试用课程名称作为索引访问grades数组,这显然无法匹配到对应分数。

正确的filter用法

利用filter回调的第二个参数(元素对应的索引),就能精准匹配对应位置的分数:

const courses = ['Math', 'Geography', 'Chemistry'];
const grades = [7, 3, 5];

// 筛选及格课程
const passedCourses = courses.filter((_, index) => grades[index] >= 5);

// 输出期望格式
console.log(`Passed = ${passedCourses.join(', ')}`);

这里的_是占位符,表示我们不需要使用第一个参数(课程名称),直接用index去取grades中对应的分数做判断即可。

另一种实现:使用reduce

如果想换一种思路,也可以用reduce来构建及格课程列表:

const passedCourses = courses.reduce((result, course, index) => {
  if (grades[index] >= 5) {
    result.push(course);
  }
  return result;
}, []);

console.log(`Passed = ${passedCourses.join(', ')}`);

两种方法都能输出你想要的结果:Passed = Math, Chemistry。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:40:38