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

自定义高阶filter函数返回布尔值而非符合条件单词的问题求助

问题解决:自定义Filter函数修正

你的问题出在myFilterFunction的逻辑上——当前它只是把回调函数返回的布尔值挨个塞进新数组,并没有根据布尔值筛选原数组的元素。不需要额外加代码,只要修改现有函数的循环逻辑就行。

修正后的代码

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];

// 修改后的高阶filter函数
let myFilterFunction = (arr) => (fn) => {
    const newArray = [];
    for (let i = 0; i < arr.length; i++) {
        // 先判断回调返回的结果,为true时才把原元素加入新数组
        if (fn(arr[i])) {
            newArray.push(arr[i]);
        }
    }
    return newArray;
};

// 调用方式不变
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);

console.log("this array only contains words that are 6 letters or more: " + printArray);

关键修改点

  • 去掉了直接push回调结果的逻辑,改成先判断回调返回的布尔值
  • 只有当fn(arr[i])返回true时,才将原数组的元素arr[i]添加到新数组中

输出结果

运行后控制台会输出:

this array only contains words that are 6 letters or more: script,function,javascript,python,coding

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:29:59