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

不使用内置.filter方法实现JavaScript数组过滤功能异常排查

错误原因

你的代码存在两个核心逻辑错误:

  • 调用测试函数fn时,传入的是数组索引i,而非索引对应的数组元素ray[i]
  • 符合过滤条件时,存入结果数组的是索引i,而非对应的数组元素ray[i]

alwaysFalse测试能够正常通过属于巧合:该函数无论接收什么入参都会返回false,结果数组始终为空,刚好符合预期,其余测试用例都会因为上述两个逻辑错误输出错误结果。

修正后的代码

function filter(ray, fn) {
    let filterArray = [];
    for (let i = 0; i < ray.length; ++i) {
        // 传入当前数组元素给测试函数判断
        if (fn(ray[i]) === true) {
            // 存入符合条件的数组元素,而非索引
            filterArray.push(ray[i]);
        }
    }
    return filterArray;
}

function isOdd(x) {
    return x % 2 === 1;
}  
function alwaysTrue(x) {
    return true;
}  
function alwaysFalse(x) {
    return false;
}

// 测试输出
console.log(filter([1,2,3,4], isOdd)); // 输出 [1,3] 符合预期
console.log(filter([1,2,3,4], alwaysTrue)); // 输出 [1,2,3,4] 符合预期
console.log(filter([1,2,3,4], alwaysFalse)); // 输出 [] 符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:24:01