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

时间:2018-09-27 18:51:18

标签: javascript node.js for-loop callback

如果我使用JavaScript bind find函数,则可以执行以下操作:

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

如您所见,在 bind loop函数中,我从find返回了 callback 。一切正常,没关系...

但是,尝试模拟类似的内容,我就这样结束了:

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一直结束。

所以,我的问题:

如何在loop时中断x===6函数并返回x的值?

2 个答案:

答案 0 :(得分:2)

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

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}`);

答案 1 :(得分:1)

您还可以使用递归编写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,就停止遍历数组的迭代