SoFunction
Updated on 2025-04-06

Simple learning of for statement loop structure in JavaScript

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:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
 &lt;meta charset="UTF-8"&gt;
 &lt;title&gt;Detailed explanation of traversal: for&lt;/title&gt;
 &lt;script src="../script/jquery-2.0."&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
 
&lt;/body&gt;
&lt;script&gt;
 var demo1Arr = ['Javascript', 'Gulp', 'CSS3', 'Grunt', 'jQuery', 'angular'];
 (function() {
 for(var i=0, len=; i&lt;len; i++) {
  if (i == 2) {
  // return; // function execution is terminated  // break; // The loop is terminated  continue; // The loop is skipped  };
  ('demo1Arr['+ i +']:' + demo1Arr[i]);
 }
 })();
&lt;/script&gt;
&lt;/html&gt;