Does the ForEach loop allow using break and continue?

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

提交回复
热议问题