获取&;TypeError: undefined不是一个函数&;用函数式编程

Getting "TypeError: undefined is not a function" with functional programming

本文关键字:函数 一个 编程 TypeError undefined 获取      更新时间:2023-09-26

我试图使用嵌套函数解决以下问题,因此我要寻找的结果是11,但它是作为countWordsInReduce函数未定义的错误出现的。该函数本身工作得很好,但由于某种原因,当使用它与减少函数我有,有一个问题。有人知道如何在reduce函数中正确使用这个吗?如有任何帮助,不胜感激。

function reduce(array, start, func){
    current = start;
    for (var i = 0; i < array.length; i++){
        current = func(current, array[i]);
    }
    return current;
}
var countWordsInReduce = function(array, start){
    var count = start;  
    count +=  array.join(", ").split(" ").length;
    return count;
}
word_array = ["hello there this is line 1", "and this is line 2"];
reduce(word_array, 0, countWordsInReduce)

这是我弄乱了一点后得到的工作版本。问题是您将当前数组索引传递给countWordsInReduce函数。

countWordsInReduce函数实际上应该做的是接受数组的下一个元素作为第一个参数,第二个参数是当前运行的总数。所以第一次调用countWordsInReduce时,传递的是第一个字符串,运行总数为0。第二次调用时,传递的是第二个字符串,总数为6。然后它会把第二个字符串的长度加进去,结果是11。

所以基本上你的reduce函数是把数组作为一个整体来看,countWordsInReduce函数只是一块一块地处理它。

function reduce(array, start, func) {
    var current = start;
    for (var i = 0; i < array.length; i++) {
        current = func(array[i], current);
    }
    return current;
}
var countWordsInReduce = function (element, base) {
    var count = base;
    count += element.split(" ").length;
    return count;
};
var word_array = ["hello there this is line 1", "and this is line 2"];
reduce(word_array, 0, countWordsInReduce);