将函数作为参数传递,该参数使用父函数的参数,但也具有自己的参数

Passing a function as argument which uses the argument of parent function but also has it's own argument

本文关键字:参数 函数 自己的 参数传递      更新时间:2023-09-26

我刚刚开始玩函数式编程,并试图将一个函数作为另一个函数的参数传递。但是,我尝试传递的函数也有这样的参数:

function splitStringBy(string, type, func) {
    // Split string by type.
    var splitArray = string.split(type);
    console.log(splitArray);
    // Do something with the array.
    func !== undefined ? func(splitArray) : null;
}

function loopArray(array, func) {
    // Loop through array.
    for (var i = 0; i < array.length; i++) {
        func(array[i]);
    }
}

我需要将splitArray传递给我的loopArray((

以下是我尝试如何称呼它:

splitStringBy($scope.textSpace, "<br>", loopArray(splitArray, function() {
            console.log('It worked!');
}));

控制台出现错误:未定义拆分数组。

您实际上不是将loopArray作为函数传递,然后将其返回值传递给splitStringBy。由于首次引用splitArray时未定义它,因此它会引发该错误。

您要做的是这样的:

function splitStringBy(string, type, func) {
    // Split string by type.
    var splitArray = string.split(type);
    console.log(splitArray);
    // Do something with the array.
    func !== undefined ? func(splitArray) : null;
}
function loopArray(func) {
    // Return function for looping.
    return function(array) {
        // Loop through array.
        for (var i = 0; i < array.length; i++) {
            func(array[i]);
        }
    }
}
splitStringBy($scope.textSpace, "<br>", loopArray(function() {
        console.log('It worked!');
}));

这称为currying,其中函数将函数作为返回值传递。 loopArray将创建一个函数,然后返回它。然后我们将新创建的函数传递给 splitStringBy ,然后由 调用它。