我正在读书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
的价值是什么?
答案 0 :(得分:3)
但
then()
和body()
功能是什么?
then
和body
是参数。它们的值取决于传递给unless
和repeat
的值。因此,为了确定值是什么(即它们是否是函数),您需要查看调用unless
和repeat
的位置以及传递给它们的值。
请注意,通常,repeat
和unless
可以多次调用。 then
和body
的值对于每个函数调用可以是不同的,但它们必须是函数期望的类型(数字,字符串,函数,...),否则它将赢得'工作正常。
他们在哪里定义?
在您的示例中,repeat
和unless
在此处调用:
repeat(3, function (n) {
unless(n % 2, function () {
document.write(n + " is even<br>");
});
});
您可以看到传递给repeat
和unless
的第二个参数确实是函数。
n
的价值是什么?
让我们看看调用函数的位置。该函数作为第二个参数传递给repeat
。 repeat
使用body
来引用第二个参数,并且它在循环中将其称为body(i)
。 i
的值为0
到times - 1
。 times
是传递给repeat
的第一个参数,在您的示例中为3
。因此,该函数将被调用多次(三次),接收值0
,1
和2
。
答案 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)
// | | | |
// |-----|--------------- |
// ------------------------|