简体   繁体   English

JavaScript 中的高阶 function

[英]Higher-order function in JavaScript

I got this code when learning about "higher-order function" in JS.我在学习 JS 中的“高阶函数”时得到了这段代码。 I can not figure out how the parameter "m" in this code would be run from 0-5?我无法弄清楚这段代码中的参数“m”如何从 0-5 运行? I understand how the function action(i) is called n times, but which part of this code give the action(i) value from 0 to (n-1)?我了解 function action(i) 是如何被调用 n 次的,但是这段代码的哪一部分给出了从 0 到 (n-1) 的 action(i) 值? Thank you.谢谢你。

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

function test(condition, result) {  
  if (condition) result();  
}  

repeat(6, m => test(m % 2 == 0, () => {  
    console.log(m);  
    } 
)  
)

I assume this is just confusing for the sake of being confusing, but let me have a try...我认为这只是为了令人困惑而令人困惑,但让我试一试......

repeat gets passed 6 and a function that will accept a number as the argument. repeat 传递了 6 和一个 function ,它将接受一个数字作为参数。 The function passed into repeat is test. function 通过重复测试。 Test gets passed in a condition and a function (result).测试在条件和 function(结果)下通过。 Repeat runs 6 times and calls test each time, passing the i in repeat to the m in test.重复运行 6 次,每次调用 test,将 i in repeat 传递给 m in test。 Each time test is run, it checks if m is even, and if so, runs the result function, which is passed in as a callback and just console.logs the value of m.每次运行测试时,它都会检查 m 是否为偶数,如果是,则运行结果 function,该结果作为回调传入,并且控制台记录 m 的值。

No matter what number is passed into repeat, m starts at 0 (from i in the for loop).无论将什么数字传递给 repeat,m 从 0 开始(从 for 循环中的 i 开始)。 This will print every even number up to, but not including the number passed in.这将打印每个偶数,但不包括传入的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM