在这个更高级别的函数中,参数n来自何处?

Goo*_*ord 2 javascript higher-order-functions

在以下来自Eloquent Javascript的第5章的代码中,参数n的值来自何处?

为什么这个函数返回任何东西.我想,我讨厌问一个非特定的,陈词滥调的问题,但我感到困惑:这个功能如何运作?

function unless(test, then) {
  if (!test) then();
}
function repeat(times, body) {
  for (var i = 0; i < times; i++) body(i);
}

repeat(3, function(n) {
  unless(n % 2, function() {
    console.log(n, "is even");
  });
});
// ? 0 is even
// ? 2 is even
Run Code Online (Sandbox Code Playgroud)

h2o*_*ooo 6

正如您所看到n的,在此回调中定义为参数:

repeat(3, function(n) {
//                 ^
Run Code Online (Sandbox Code Playgroud)

让我们进入repeat功能:

function repeat(times, body) {
    for (var i = 0; i < times; i++) body(i);
    // We're calling our callback with i ^
}
Run Code Online (Sandbox Code Playgroud)

这里times将成为3body将成为我们的匿名函数(回调).因此,当我们打电话body(i),我们实际上调用以下(切换n出有i,因为我们调用body(i)):

unless(i % 2, function() {
    console.log(i, "is even");
})
Run Code Online (Sandbox Code Playgroud)

这是您解开的整个资源:

var times = 3;

for (var i = 0; i < times; i++) {
    var n = i; // We're renaming "i" (from body(i)) to "n" (in function(n))

    if (!(n % 2)) {
        console.log(n, "is even");
    }
}
Run Code Online (Sandbox Code Playgroud)