Simply learn the for statement loop structure in JavaScript

  • 2020-10-23 20:00:12
  • OfStack

You can look directly at the example, too many, very simple


(function() {
  for(var i=0, len=demoArr.length; i<len; i++) {
    if (i == 2) {
      // return;  //  The function execution is terminated 
      // break;  //  The loop is terminated 
      continue; //  The loop is skipped 
    };
    console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
  }
})();

There are a few things to note about the for loop

i in the for loop still exists in the scope after the end of the loop. In order to avoid affecting other variables in the scope, it is isolated by the way of function self-execution ()(); Avoid for(var i=0; i < demo1Arr.length; i++){}, where the array length is calculated each time, is less efficient than above. Variable declarations can also be executed before for to improve readability var i = 0, len = demo1Arr.length; for(; i < len; i++) {};

There are several ways to get out of the loop

The return function execution is terminated The break loop is terminated The continue loop is skipped

Complete examples:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title> Traverse, : for</title>
 <script src="../script/jquery-2.0.3.js"></script>
</head>
<body>
 
</body>
<script>
 var demo1Arr = ['Javascript', 'Gulp', 'CSS3', 'Grunt', 'jQuery', 'angular'];
 (function() {
 for(var i=0, len=demo1Arr.length; i<len; i++) {
  if (i == 2) {
  // return;  //  The function execution is terminated 
  // break;  //  The loop is terminated 
  continue; //  The loop is skipped 
  };
  console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
 }
 })();
</script>
</html>


Related articles: