Home >Web Front-end >JS Tutorial >The difference between returning false when JavaScript uses forEach() and jQuery uses each to traverse an array
This article mainly introduces the difference between returning false when JavaScript uses forEach() and jQuery uses each to traverse the array. It is very good. Friends who need it can refer to it
Native js uses forEach() and jquery uses The difference between each() traversing the array and return false:
1. Use each() to traverse the array a, as follows:
var a=[20,21,22,23,24]; $.each(a, function(index,val) { console.log('index='+index); if(index==2){ return false; } console.log('val='+val); });
The results are as follows:
#It can be seen from the running effect that return is equivalent to break in the loop, directly ending the entire loop.
2. Use forEach() to traverse array a, as follows:
var a=[20,21,22,23,24]; a.forEach(function(val,index){ console.log('index='+index); if(index==2){ return false; } console.log('val='+val); });
The result is as follows:
It can be seen from the running effect that return is equivalent to continue in the loop, jumping out of the current loop and continuing the subsequent loop traversal.
I have also checked some information. We can end the entire forEach() loop by writing our own judgment statements, or use for() loop traversal.
Related recommendations:
AngularJS uses the Post method to pass json parameters (code attached)
JavaScript uses import and require packaging examples share
The above is the detailed content of The difference between returning false when JavaScript uses forEach() and jQuery uses each to traverse an array. For more information, please follow other related articles on the PHP Chinese website!