代码之家  ›  专栏  ›  技术社区  ›  NewQode10

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

  •  0
  • NewQode10  · 技术社区  · 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);
    
    2 回复  |  直到 1 年前
        1
  •  1
  •   Renz Salanga    1 年前

    您正在推送条件的布尔表达式结果,而是将其用作推送所需单词的条件,如下所示

    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);
    
        2
  •  0
  •   ARUN CV    1 年前

    您将作为参数传递的函数的结果附加到数组中,而不是传递数组的元素

    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++) {
     
          fn(arr[i]) && newArray.push(arr[i]);
    //if the condition is true we are adding the element to newArray 
    
        }
        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);