Home >Web Front-end >JS Tutorial >Simply learn the for statement loop structure in JavaScript_Basic knowledge

Simply learn the for statement loop structure in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:32:531442browse

You can just look at the example, it’s used too much, it’s very simple

(function() {
  for(var i=0, len=demoArr.length; i<len; i++) {
    if (i == 2) {
      // return;  // 函数执行被终止
      // break;  // 循环被终止
      continue; // 循环被跳过
    };
    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 loop ends. In order to avoid affecting other variables in the scope, it is isolated using self-execution of the function ()();
  • Avoid using for(var i=0; i
  • var i = 0, len = demo1Arr.length;
  • for(; i

There are several ways to break out of the loop

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

Full example:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>遍历详解: 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;  // 函数执行被终止
  // break;  // 循环被终止
  continue; // 循环被跳过
  };
  console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
 }
 })();
</script>
</html>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn