首页 > 解决方案 > How function unless works int the example in Chapter 5 Higher-Order Functions from the Eloquent JavaScript 3rd edition?

问题描述

The function repeat seems to take n = 0 as the argument and I don't know why. Can someone explain it to me, please?

function unless(test, then) {
  
       if (!test) then();
}

repeat(3, n => {
  
     unless(n % 2 == 1, () => {
    
          console.log(n, "is even");
      });
});

// → 0 is even

// → 2 is even

标签: javascript

解决方案


You're passing two arguments to function unless one is Boolean and another is function

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

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

Here n % 2 == 1 is first argument and () => console.log(n, "is even"); } is second

and in your function unless

function unless(test, then) {

       if (!test) then();
}

We are first checking the if the test is false than only run the function passed as argument


推荐阅读