代码之家  ›  专栏  ›  技术社区  ›  robe007 Leo Aguirre

如何在for循环中从回调内部中断

  •  0
  • robe007 Leo Aguirre  · 技术社区  · 7 年前

    bind 函数 find 在javascript中,我可以执行以下操作:

    const _array = [4,10,6,5,20];
    
    const loop = Array.prototype.find.bind(_array);
    const r = loop(function (x) {
        return x === 6;
    });
    
    console.log(`Final result => ${r}`); // here prints: Final result => 6
    

    如你所见,在 loop 功能我有一个 从返回 . 一切正常。。。

    function loop(a,callback) {
        for(i=0;i<a.length;i++)
            callback(a[i]);
    };
    
    const r = loop([4,10,6,5,20], function (x) {
        console.log("x value", x);
        return x===6; // need to break the loop function and return to 'r' the 'x' value
    });
    
    console.log(`Final result => ${r}`); // here would print the value of x, that would be 6
    

    我得到:

    x value 4
    x value 10
    x value 6
    x value 5
    x value 20
    undefined
    

    这是什么意思 return x===6 r 函数工作不正常,因为 for-loop 一直到最后。

    什么时候起作用 x===6 并返回 x ?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Nicholas Tower    7 年前

    检查回调返回的值,然后决定是否继续:

    function loop(a, callback) {
      for (let i = 0; i < a.length; i++) {
        const found = callback(a[i]);
        if (found) {
          return a[i];
        }
      }
    }
    
    const r = loop([4,10,6,5,20], function (x) {
      console.log("x value", x);
      return x===6;
    });
    
    console.log(`Final result => ${r}`);
        2
  •  1
  •   Mulan    7 年前

    你也可以写 find 使用递归

    const find = (f, [ x, ...xs ]) =>
      x === undefined
        ? null
      : f (x) === true
        ? x
      : find (f, xs)
    
    console.log
      ( find
          ( x => x > 8
          , [ 5, 7, 9, 3, 1 ]
          )
          // 9
          
      , find
          ( x => x < 4
          , [ 5, 7, 9, 3, 1 ]
          )
          // 3
      )

    const find = (f, xs = [], i = 0) =>
      i >= xs.length
        ? null
      : f (xs[i]) === true
        ? xs[i]
      : find (f, xs, i + 1)
    

    在这两种情况下,只要 f 返回true