We hear a lot about loops, especially for loops. So what, in fact, are they? They’re just pieces of code that repeat the same commands several times, until you reach a desired conclusion, without getting you bored out of your mind, repeating your code. This is how we JavaScript guys do it.

Syntax

You will definitely have to know the syntax of for loops and that goes like this:

1 for ([initialization]; [condition]; [final-expression]) statement

You’ll see in the examples how each of these clauses is translated into code. So let’s start right away.

Using simple for loops

The most typical way to use for loops is counting. You just need to tell the loop where to start, where to finish, and with what pace to count. This is how the code goes for counting and printing in the screen odd numbers from one to ten:

1 for (var i = 1; i < 10; i+2) {
2     console.log(i);
3 }

According to the syntax structure we gave you above, you can now easily distinguish that we have first declared and initialized the variable with the value 1. We have set the condition, which in our case is to not count odd numbers greater than 10, and the final one is the pace, and since the two closest odd numbers only differ by 2 the final expression is i+2. Notice that we start the loop with an odd number.

Removing for loop’s clauses

One way to put for loops in good use would be to optimize them, by removing the expressions.Each one of them can be omitted, or you can even omit them all. We will be using the same code of the example above, only we’ll modify it according to the thing we want to show you, so that you can draw the differences and understand it more. Firstly, we’ll show you when and how can you remove the initialization expression. Have a look at the code to see how it changes:

1 var i = 1;
2 for (; i < 10; i+2) {
3     console.log(i);
4 }

You will definitely notice that we have removed the initialization expression, but the variable is initialized outside the loop before we write the code for the loop. Also what’s important here is that the place where the expression we removed was is still there, even though it’s now empty. It’s not correct to remove the semicolon saving that space.

Now it’s time to show you how to use a for loop with all three blocks removed. This is the code:

1 i=0;
2 for (;;) {
3     if (i > 3) break;
4     console.log(i);
5     i++;
6 }

You are obliged to declare an initialize the variable before writing the rest of the loop’s code. If you don’t want to put a condition or a way to get out of the loop, you would be building an infinite loop. But if this is not your intention then you will have to put a condition and an expression that changes the value of the variable, as we have done in the previous code snippet.

for loops and break;

If you were careful in watching the code snippets above you will see something that we did not explain: the expression break;. That expression is used to jump out of the loop, which means that it takes the command right after the loop, without executing the rest of it, but instead doing whatever code is next. Here’s an example of how you can use it:

1 var text = ""
2 var i;
3 for (i = 0; i < 10; i++) {
4     if (i == 3) {break;}
5     text += "The number is " + i + "<br>";
6 }

This code snippet prints out the value of the i variable, and increments it by one. When the value of i reaches 3, it breaks out of the loop. That is how the break; expression operates.

for loops and continue;

The continue; expression is similar to break; only this one only breaks out of the current iteration, and into the next one, not necessarily out of the loop. Here’s the modified example:

1 var text = ""
2 var i;
3 for (i = 0; i < 10; i++) {
4     if (i == 3) {continue;}
5     text += "The number is " + i + "<br>";
6 }

Instead of break; we have used continue; and the difference is that the next iteration to be executed is not the one after the loop, it’s the one after the iteration containing continue;.

for…in loops

The for...in loops are a way of iterating only the properties of different objects.It’s sytax is like this:

1 for (var variable in objectExpression) {statement}

Any expression that evaluates to an object can be used as objectExpression, and this object’s properties are the ones to be iterated. On each iteration, the property names are assigned to variables, and then the statement is executed.See the example below:

1 var myObj = {a: 1, b: 2, c: 3},
2     myKeys = [];
3   
4 for (var property in myObj) {
5     myKeys.push(property);
6 }
7   
8 myKeys;
9  
10 //['a','b','c'];

Note that the properties’ values are actually strings, so whatever action you want to do with, or on them in the statement block, you will have to think of them as such.

Using for with an empty statement

The awesome part about JavaScript is that almost every modification of the code leads you somewhere useful. That is the case with the following code, which we’d like you to see first and discuss later:

1 function showOffsetPos (sId) {
2  
3     // initialization
4     var nLeft = 0, nTop = 0;
5  
6     // condition
7     for (var oItNode = document.getElementById(sId);
8         // final-expression
9          oItNode;
10          nLeft += oItNode.offsetLeft,
11          nTop += oItNode.offsetTop,
12  
13           // empty statement
14          oItNode = oItNode.offsetParent) ;
15  
16     console.log("Offset position of \"" + sId + "\" element:\n left: "
17         + nLeft + "px;\n top: " + nTop + "px;");
18 }
19  
20 showOffsetPos("content");

This loop calculates the offset position of a node in the final-expression section, therefore making the use of a statement block useless, so the empty statement is used instead.

Download the source code

This was an example of for loops in JavaScript.

http://www.webcodegeeks.com/javascript/javascript-for-loop-example/

转载于:https://www.cnblogs.com/davidwang456/p/4133389.html

javascript-for-loop-example--reference相关推荐

  1. 试图解释清楚【JavaScript Event Loop】

    本篇文章较长,让网络飞一会再看~ 本文结构 - 带着问题看这篇文章 - JS Runtime的几个概念 - Event Loop事件循环 - UI Rendering Task - 可视化:event ...

  2. javascript --- event loop

    栗子1 求下面函数的输出 console.log('script start');setTimeout(() => {console.log('setTimeoout'); }, 0);Prom ...

  3. javascript Event loop

    感谢Philip Roberts的演讲Help, I'm stuck in an event-loop让我对javascript的运行机制有一定的理解. javascript是一种单线程语言,所以任务 ...

  4. JavaScript event loop事件循环 macrotask与microtask

    macrotask  姑且称为宏任务,在很多上下文也被简称为task.例如: setTimeout, setInterval, setImmediate, I/O, UI rendering. mic ...

  5. JAVA script 循环 图片_深入分析JavaScript 事件循环(Event Loop)

    事件循环(Event Loop),是每个JS开发者都会接触到的概念,但是刚接触时可能会存在各种疑惑. 众所周知,JS是单线程的,即同一时间只能运行一个任务.一般情况下这不会引发问题,但是如果我们有一个 ...

  6. javascript事件轮询(event loop)详解

    英语原文摘自:http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ The JavaScript Eve ...

  7. Airbnb JavaScript Style Guide

    转自: https://github.com/airbnb/javascript/blob/master/README.md Airbnb JavaScript Style Guide() { A m ...

  8. 最佳JavaScript示例

    JavaScript is the most widely used scripting language on earth. Here are some examples of key syntax ...

  9. 【转载】浏览器事件循环机制(event loop)

    首先,本文转自https://juejin.im/post/5afbc62151882542af04112d 当我看完菲利普·罗伯茨的 javascript event loop的演讲的时候,就对于事 ...

  10. 【译】理解Javascript函数执行—调用栈、事件循环、任务等

    原文作者:Gaurav Pandvia 原文链接:medium.com/@gaurav.pan- 文中部分链接可能需要梯子. 欢迎批评指正. 现如今,web开发者(我们更喜欢被叫做前端工程师)用一门脚 ...

最新文章

  1. mysql 在存储过程出现的问题,记录一下
  2. 制作keil5的pack
  3. 队列顺序结构C/C++实现(数据结构严蔚敏版)
  4. 【Spring学习】spring提供的三种定时任务
  5. html hover 效果,CSS八种让人眼前一亮的HOVER效果的示例代码
  6. matlab在电力系统潮流计算程序,大神们,求个电力系统潮流计算的matlab程序。
  7. linux db2在线备份,DB2 pureScale在线备份恢复实例
  8. python条件语句代码例子_Python 炫技操作:条件语句的七种写法
  9. Pro Git读书笔记 - 分支
  10. 知识分享|日本面试常考问题+巧妙回答 ②
  11. MATLAB生成正弦码表
  12. stm32f205开发记录
  13. 一张纸厚度是多少毫米_一本书的厚度大约是多少,一张纸的厚度大约是十分之一毫米,一本书...
  14. 微信公众号获取永久素材
  15. 如何关闭mysql secure_file_priv
  16. 测试03:2022上半年:无处安放的空虚感
  17. Android 9 ServerManger源码分析
  18. html a 冒泡点击,子元素点击不能冒泡到父元素
  19. 航姿参考系统(AHRS)
  20. vue项目中 高德地图总是出不来的问题

热门文章

  1. python的迭代器指向第一个字符_python(七)字符串格式化、生成器与迭代器
  2. python大神写的代码_初学Python,只会写简单的代码。手头有份Python代码,但是调用C模块生成的.pxd和.pyx文件,运行过程总报错,希望大神指点,调试前该做哪些工作呢?...
  3. linux软件升级直接替换,Linux几个命令的升级替代品
  4. java 市场_java市场前景怎样?
  5. 关中断解决任务间资源共享问题
  6. matlab计算电路环流,双反星形整流电路并联运行环流分析
  7. c3p0 参数 模糊查询_MySQL模糊查询用法大全(正则、通配符、内置函数等)
  8. java监听变量的变化_[Java学习小记]使用PropertyChangeSupport来监听变量的变化
  9. jetson nano 实现车牌识别
  10. python 去除字符串里所有标点符号