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
?