簡體   English   中英

如何從for循環的回調內部中斷

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM