You can directly look at the examples, it's too many to use, it's very simple
(function() { for(var i=0, len=; i<len; i++) { if (i == 2) { // return; // function execution is terminated // break; // The loop is terminated continue; // The loop is skipped }; ('demo1Arr['+ i +']:' + demo1Arr[i]); } })();
Regarding the for loop, there are some points to pay attention to
- i in the for loop still exists in the scope after the loop ends. In order to avoid affecting other variables in the scope, it is isolated by using the function self-execution method ()();
- Avoid using for(var i=0; i<; i++){}, such array length is calculated every time, which is less efficient than the above method. You can also place variable declarations in front of for to perform to improve reading
- var i = 0, len = ;
- for(; i<len; i++) {};
There are several ways to break out of the loop
- The return function execution is terminated
- break loop is terminated
- The continue loop is skipped
Complete example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Detailed explanation of traversal: for</title> <script src="../script/jquery-2.0."></script> </head> <body> </body> <script> var demo1Arr = ['Javascript', 'Gulp', 'CSS3', 'Grunt', 'jQuery', 'angular']; (function() { for(var i=0, len=; i<len; i++) { if (i == 2) { // return; // function execution is terminated // break; // The loop is terminated continue; // The loop is skipped }; ('demo1Arr['+ i +']:' + demo1Arr[i]); } })(); </script> </html>