简体   繁体   English

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

[英]How to break from inside a callback in a for-loop

If I bind the function find in javascript, I can do the following: 如果我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

As you can see, in the binded loop function I have a callback returned from find . 如您所见,在绑定 loop函数中,我从find返回了一个回调 Everything works and it's ok ... 一切正常,没关系...

But, trying to simulate something like that I ended with this: 但是,尝试模拟类似的结果,我以此结束:

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

and I get: 我得到:

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

what means that the return x===6 inside the r function is not working correctly, because the for-loop continues to the end. 这意味着r函数内部的return x===6不能正常工作,因为for-loop一直持续到最后。

So, my question: 所以,我的问题是:

How can I break the loop function when x===6 and return the value of x ? x===6时如何中断loop函数并返回x的值?

Check what value is returned by the callback, and then decide whether to continue or not: 检查回调返回的值,然后决定是否继续:

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

You can also write find using recursion 您还find使用递归编写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 ) 

Instead of destructuring assignment, an index parameter can be used 代替破坏分配,可以使用索引参数

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

In both cases, iteration through the array stops as soon as f returns true 在这两种情况下,只要f返回true,就停止对数组的迭代

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

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