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

使用filter方法实现数组元素翻倍失败,求代码修正方案

问题修正说明

错误原因

你误用了数组方法:

  • filter 方法的核心作用是筛选数组元素,它会根据传入函数的返回值(布尔类型)决定是否保留原元素。因为你传入的doubleArr函数返回的是num*2,所有非0数字都会被视为true,所以最终返回的是原数组的全部元素,完全没实现数值翻倍的效果。
  • 要完成数组元素的转换操作,应该使用map方法,它会遍历数组的每个元素,执行转换逻辑后返回新的结果数组。

修正后的代码

let arr = [1, 4, 2, 7, 3, 9, 4, 15];
function doubleArr(num) {
  return num * 2;
}
let result = arr.map(doubleArr);
console.log(result); // 输出: [2,8,4,14,6,18,8,30]

也可以写成更简洁的箭头函数形式:

let arr = [1, 4, 2, 7, 3, 9, 4, 15];
let result = arr.map(num => num * 2);
console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:42:05