【问题标题】:Passing a function as argument which uses the argument of parent function but also has it's own argument传递一个函数作为参数,它使用父函数的参数但也有它自己的参数
【发布时间】:2016-05-28 04:04:45
【问题描述】:

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

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!');
}));

控制台出现错误:splitArray 未定义。

【问题讨论】:

    标签: javascript function callback functional-programming arguments


    【解决方案1】:

    您实际上是在调用它,而不是将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!');
    }));
    

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

    【讨论】:

    • 所以我猜如果你想对 loopArray 中的函数做同样的事情,你也会这样做,对吧?
    • 是的,但我真的不知道为什么在这种情况下你需要双重咖喱。
    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2010-11-20
    相关资源
    最近更新 更多