Does the ForEach loop allow using break and continue?

后端 未结 2 1355
-上瘾入骨i
-上瘾入骨i 2021-02-19 07:42

Does the ForEach loop allow us to use break and continue?

I\'ve tried using both but I received an error:

Illegal          


        
2条回答
  •  暖寄归人
    2021-02-19 08:31

    No, it doesn't, because you pass a callback as a return, which is executed as an ordinary function.

    Let me be clear:

    var arr = [1,2,3];
    arr.forEach(function(i) {
        console.log(i);
    });
    
    // is like
    
    var cb = function(i) {
        console.log(i);
        // would "break" here do anything?
        // would "continue" here do anything?
        // of course not.
    }
    
    for(var j = 0; j < arr.length; j++) {
        cb(arr[j]);
    }
    

    All forEach does is call a real, actual function you give to it repeatedly, ignore how it exits, then calls it again on the next element.

    In that callback function if you return it will incidentally work like continue in the case of forEach. Because the rest of the function won't execute that time, and it will be called again. There is no analogue of break.

    Ruby supports this flexibility, using blocks/procs instead of methods/lambdas.

    Per Mozilla's documentation:

    Note : There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some. See example below.

    every and some are exactly like forEach, except they pay attention to the return value of the callback. every will break on a falsey value and some will break on a truthy value, since they shortcircuit. They are exactly analogous to && and ||. && tests whether every expression is truthy, || tests for whether some is, which should help you remember how short-circuiting works with every and some. When in doubt, try it.

提交回复
热议问题