javascript部分函数、参数

javascript部分函数、参数,javascript,Javascript,我试图理解部分函数。我找到了这个例子(),我无法完全理解 function partial(f) { console.log(f) // tip(p,check) var args = Array.prototype.slice.call(arguments, 1); //0.2 var test_args = Array.prototype.slice.call(arguments); console.warn(test_args) // [tip(p,che

我试图理解部分函数。我找到了这个例子(),我无法完全理解

function partial(f) {
    console.log(f) // tip(p,check)
    var args = Array.prototype.slice.call(arguments, 1); //0.2

    var test_args = Array.prototype.slice.call(arguments);
    console.warn(test_args) // [tip(p,check), 0.2]

    return function () {
        console.warn(arguments) //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ...
        //where do these arguments come from? why don't appear at test_args?

        var other_args = Array.prototype.slice.call(arguments); //[120, 0, [120, 90, 180]] [90, 0, [120, 90, 180]] ...

        console.log(args.concat(other_args)) // added percentage to array[0.2, 120, 0, [120, 90, 180]]

        return f.apply(null, args.concat(other_args)); //we execute tip with all the arguments (only 2 first will be used)
    }
}

function tip(percentage, check) {
    return check * percentage
}

[120, 90, 180].map(partial(tip, 0.2)); //[24, 18, 36]
这些论点从何而来?为什么不出现在测试中

因为它是一个新函数-返回的函数-它有一个新的
参数
对象。您可以在这里查看:

var tipper = partial(tip,0.2);
[120, 90, 180].map(function(el) {
     console.log(arguments); // here they are!
     return tipper(el);
});

在编程语言理论中,这被称为部分应用程序。它基本上接受需要n个参数和n-k个参数的函数,并通过部分应用这些提供的n-k个参数来返回具有k个参数的函数

以伪代码为例

function mul(x, y)
    return x*y

function mul2
    return mul(2)

var a = f(1,2); // 3
var b = mul2(4); // 8
尽管该函数有两个参数(n),但您可以通过仅应用一个参数(n-k)从中生成另一个函数。新函数将只需要一个参数(k)

您的
部分
接受函数及其
参数
。它将这些参数存储在
args
变量中。然后它返回内部函数,该函数本身接受它的参数,但由于它必须将顶级函数的n-k个参数与内部函数的k个参数组合在一起,因此有
concat
,完整列表将传递给原始函数


编辑:正如Andreas在评论中指出的,这不是所谓的“套路”。答案的其余部分仍然有效。

根据您的问题,您需要仔细阅读,而不是部分函数。(并再次检查您在注释中记录的值,
[90,0,[120
应该是
[90,1,[120
),
function mul(x, y)
    return x*y

function mul2
    return mul(2)

var a = f(1,2); // 3
var b = mul2(4); // 8