javascript中的高阶函数

时间:2016-05-18 15:13:27

标签: javascript function

我正在读书Eloquent来学习javascript。我遇到了这个例子

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

我知道函数可以作为参数传递,并且可以在彼此内部。 但是then()body()功能是什么?他们在哪里定义? n的价值是什么?

3 个答案:

答案 0 :(得分:3)

  

then()body()功能是什么?

thenbody是参数。它们的值取决于传递给unlessrepeat的值。因此,为了确定值是什么(即它们是否是函数),您需要查看调用unlessrepeat的位置以及传递给它们的值。

请注意,通常,repeatunless可以多次调用。 thenbody的值对于每个函数调用可以是不同的,但它们必须是函数期望的类型(数字,字符串,函数,...),否则它将赢得'工作正常。

  

他们在哪里定义?

在您的示例中,repeatunless在此处调用:

repeat(3, function (n) {
    unless(n % 2, function () {
        document.write(n + " is even<br>");
    });
});

您可以看到传递给repeatunless的第二个参数确实是函数。

  

n的价值是什么?

让我们看看调用函数的位置。该函数作为第二个参数传递给repeatrepeat使用body来引用第二个参数,并且它在循环中将其称为body(i)i的值为0times - 1times是传递给repeat的第一个参数,在您的示例中为3。因此,该函数将被调用多次(三次),接收值012

答案 1 :(得分:0)

这是一个小解释。

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

// in here you also pass 2 params to repeat.
// 3 and an anonymous function, the function is the argument 'body' in repeat
repeat (3 , function ( n ) {
  // as you can see here - you pass 2 params to unless, 
  // 1 is the result of n %2, and an anonymous  function, the function is the argument
  // "then" in unless.
  unless ( n % 2 , function () {
    console . log (n , " is even ") ;

  }) ;
}) ;

n的值从0变为3,它将变为0,1,2

此外,由于您是初学者,我建议您使用https://jsfiddle.net/来测试内容。

答案 2 :(得分:0)

在您的示例中,您拥有unless函数的签名:

function unless ( test , then ) {
// code here
}

测试然后都被称为参数,并根据您拨打unless时传递的参数进行更改

例如:

 function first(){}
 function second(){}

 unless(first,second)

表示除非是函数原因,否则测试 测试替换为第一个功能然后第二个功能替换为unless < / p>

// unless(test,then) => unless(first,second)
//         |     |              |        |
//         |-----|---------------        |     
//               ------------------------|