What is the meaning of the `return` keyword in the `forEach` function?
P粉964682904
P粉964682904 2023-08-21 17:58:20
0
2
576
<p><br /></p> <pre class="brush:js;toolbar:false;">$('button').click(function () { [1, 2, 3, 4, 5].forEach(function (n) { if (n == 3) { // This should break and nothing should pop up return false } alert(n) }) })</pre> <pre class="brush:html;toolbar:false;"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> ;</script> <button>Click me</button></pre> <p><br /></p> <p>My question is: Why does it still pop up the next number even though I call <code>return</code>? Like: <em>Ignore the code below and continue to the next element</em></p>
P粉964682904
P粉964682904

reply all(2)
P粉245003607

The return statement return will exit the current function, but the loop will continue, so you will get the "next" skipped if statement and pop 4 Item...

If you need to stop the loop, you should use a normal for loop like this:

$('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 break and continue in js here: http://www.w3schools.com/js/js_break.asp

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template