What is the meaning of the `return` keyword in the `forEach` function?
P粉964682904
2023-08-21 17:58:20
<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>
The return statement
return
will exit the current function, but the loop will continue, so you will get the "next" skippedif
statement and pop 4 Item...If you need to stop the loop, you should use a normal
for
loop like this:You can read more about break and continue in js here: http://www.w3schools.com/js/js_break.asp
From Mozilla Developer Network: