簡體   English   中英

除非在Eloquent JavaScript第3版的第5章高階函數中的示例中起作用,否則函數如何?

[英]How function unless works int the example in Chapter 5 Higher-Order Functions from the Eloquent JavaScript 3rd edition?

函數repeat似乎以n = 0作為參數,我不知道為什么。 有人可以向我解釋一下嗎?

function unless(test, then) {

       if (!test) then();
}

repeat(3, n => {

     unless(n % 2 == 1, () => {

          console.log(n, "is even");
      });
});

//→0是偶數

//→2是偶數

你將兩個參數傳遞給函數,除非一個是Boolean ,另一個是function

unless(n % 2 == 1, () => {

          console.log(n, "is even");
});

這里n % 2 == 1是第一個參數而() => console.log(n, "is even"); } () => console.log(n, "is even"); }是第二

並在你的功能,除非

function unless(test, then) {

       if (!test) then();
}

我們首先檢查測試是否為假,而不僅僅是運行作為參數傳遞的函數

我剛才意識到函數重復是在本章之前預先定義的。

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

repeat(3, console.log);
// → 0
// → 1
// → 2

這就是為什么它從n = 0開始,因為在循環中i被初始化為0並且函數被評估為long i小於n。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM