Does the ForEach loop allow using break and continue?

后端 未结 2 1354
-上瘾入骨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:13

    As already answered, you cannot use continue or break inside a JavaScript Array.prototype.forEach loop. However, there are other options:

    Option 1

    Use the jQuery .each() function (Reference).

    Simply return true to continue, or return false to break the loop.

    Option 2

    Just use return to continue or throw new Error() to break. I don't necessarily recommend doing it this way, but it's interesting to know that this is possible.

    try {
        [1, 2, 3, 4].forEach(function(i) {
    
            if (i === 2) {
                return; // continue
            }
    
            if (i === 3) {
                throw new Error(); // break
            }
    
            console.log(i);
        });
    }
    catch (e) {
    }
    

    The expected result is just 1

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题