• 赚钱入口【需求资源】限时招募流量主、渠道主,站长合作;【合作模式】CPS长期分成,一次推广永久有收益。主动打款,不扣量;

Javascript:如何将函数作为参数传递?

JavaScript cps12345 1年前 (2020-07-22) 225次浏览 0个评论

Javascript:如何将函数作为参数传递?

该代码应该能够成功运行传递到循环函数中的函数值。

  function loop(value, test, update, body){
    for (let i = 0; i < 10; i++){
      if (test(i, value)) break;
      update(value);
      console.log(body(i));
    }
  }

  loop(5, (i, value) => { return i > value }, (value) => {return value + 1},

解决方法

<code><span class="kwd">function</span><span class="pln"> loop</span><span class="pun">(</span><span class="pln">test</span><span class="pun">,</span><span class="pln"> update</span><span class="pun">,</span><span class="pln"> body</span><span class="pun">)</span> <span class="pun">{</span>
  <span class="kwd">for</span> <span class="pun">(</span><span class="kwd">let</span><span class="pln"> i </span><span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun"><</span> <span class="lit">10</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span> <span class="pun">{</span>
    <span class="kwd">if</span> <span class="pun">(</span><span class="pln">test</span><span class="pun">(</span><span class="pln">i</span><span class="pun">))</span>
      <span class="kwd">break</span><span class="pun">;</span><span class="pln">
    
    i </span><span class="pun">=</span><span class="pln"> update</span><span class="pun">(</span><span class="pln">i</span><span class="pun">);</span><span class="pln">
    
    console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">body</span><span class="pun">(</span><span class="pln">i</span><span class="pun">));</span>
  <span class="pun">}</span>
<span class="pun">}</span><span class="pln">

loop</span><span class="pun">((</span><span class="pln">i</span><span class="pun">)</span> <span class="pun">=></span> <span class="pun">{</span>
  <span class="kwd">if</span> <span class="pun">(</span><span class="pln">i </span><span class="pun">></span> <span class="lit">7</span><span class="pun">)</span> <span class="kwd">return</span> <span class="kwd">true</span><span class="pun">;</span>
<span class="pun">},</span> <span class="pun">(</span><span class="pln">i</span><span class="pun">)</span> <span class="pun">=></span> <span class="pun">{</span>
  <span class="kwd">return</span><span class="pln"> i</span><span class="pun">++</span>
<span class="pun">},</span> <span class="pun">(</span><span class="pln">i</span><span class="pun">)</span> <span class="pun">=></span> <span class="pun">{</span>
  <span class="kwd">return</span><span class="pln"> i </span><span class="pun">*</span> <span class="lit">2</span><span class="pun">;</span>
<span class="pun">});</span></code>
喜欢 (0)

您必须 登录 才能发表评论!