What does `return` keyword mean inside `forEach` function?

This question already has an answer here:

  • How to short circuit Array.forEach like calling break? 24 answers

  • From MDN:

    Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.


    The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

    If you need to stop the looping, you should just use a plain for loop like so:

    $('button').click(function () {
       var arr = [1, 2, 3, 4, 5];
       for(var i = 0; i < arr.length; i++) {
         var n = arr[i]; 
         if (n == 3) {
             break;
          }
          alert(n);
       })
    })
    

    You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

    链接地址: http://www.djcxy.com/p/70042.html

    上一篇: 如何从JavaScript中的foreach循环中跳出来

    下一篇: `for`功能里的`return`关键词是什么意思?