This question already has an answer here:
$('button').click(function () {
[1, 2, 3, 4, 5].forEach(function (n) {
if (n == 3) {
// it should break out here and doesn't alert anything after
return false
}
alert(n)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>
My question: Why does it still alert next number although I call return
? Just like: Ignore the code below and continue with next element
From the Mozilla Developer Network:
The
return
exits the current function, but the iterations keeps on, so you get the "next" item that skips theif
and alerts the 4...If you need to stop the looping, you should just use a plain
for
loop like so:You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp