简体   繁体   中英

How to break from inside a callback in a for-loop

If I bind the function find in javascript, I can do the following:

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 . 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.

So, my question:

How can I break the loop function when x===6 and return the value of 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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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