[英]How to break from inside a callback in a for-loop
如果我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
函數中,我從find
返回了一個回調 。 一切正常,沒關系...
但是,嘗試模擬類似的結果,我以此結束:
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
這意味着r
函數內部的return x===6
不能正常工作,因為for-loop
一直持續到最后。
所以,我的問題是:
當x===6
時如何中斷loop
函數並返回x
的值?
檢查回調返回的值,然后決定是否繼續:
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}`);
您還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 )
代替破壞分配,可以使用索引參數
const find = (f, xs = [], i = 0) =>
i >= xs.length
? null
: f (xs[i]) === true
? xs[i]
: find (f, xs, i + 1)
在這兩種情況下,只要f
返回true,就停止對數組的迭代
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.