为什么我的高阶函数返回 true 和 false?

问题描述 投票:0回答:1

我必须创建自己的高阶 filter() 函数来过滤 10 个单词的数组,该数组仅返回具有 6 个或更多字母的单词,但我的函数仅返回 true 和 false,并且不会忽略不是 6 个或更多字母的单词而不是实际返回新数组中的单词。是否添加额外的代码来执行该函数?

而且我也不允许使用内置的过滤功能。

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
//myFilterFunction(HOF) takes an array (arr) and hypothetical function (fn) as arguments//
let myFilterFunction = (arr) => (fn) => {
    const newArray = [];
    for (let i = 0; i < arr.length; i++) {
        newArray.push(fn(arr[i]));
    }
    return newArray; //return a array
};
//myFilterFunction is used with an anonymous function to return whether each word is 6 or more   letters//
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
//Output the result to the console//
console.log("this array only contains words that are 6 letters or more: " + printArray);
javascript arrays function callback higher-order-functions
1个回答
0
投票

您正在推送条件的布尔表达式结果,而不是使用它作为条件(如果您愿意的话)

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
//myFilterFunction(HOF) takes an array (arr) and hypothetical function (fn) as arguments//
let myFilterFunction = (arr) => (fn) => {
    const newArray = [];
    for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i])) {
            newArray.push(arr[i]);   
        }
    }
    return newArray; //return a array
};
//myFilterFunction is used with an anonymous function to return whether each word is 6 or more   letters//
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
//Output the result to the console//
console.log("this array only contains words that are 6 letters or more: " + printArray);
© www.soinside.com 2019 - 2024. All rights reserved.