[英]How function unless works int the example in Chapter 5 Higher-Order Functions from the Eloquent JavaScript 3rd edition?
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.