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) { |
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:
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:
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:
3 |
for (i = 0; i < 10; i++) { |
5 |
text += "The number is " + i + "<br>"; |
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:
3 |
for (i = 0; i < 10; i++) { |
4 |
if (i == 3) {continue;} |
5 |
text += "The number is " + i + "<br>"; |
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}, |
4 |
for (var property in myObj) { |
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) { |
4 |
var nLeft = 0, nTop = 0; |
7 |
for (var oItNode = document.getElementById(sId); |
10 |
nLeft += oItNode.offsetLeft, |
11 |
nTop += oItNode.offsetTop, |
14 |
oItNode = oItNode.offsetParent) ; |
16 |
console.log("Offset position of \"" + sId + "\" element:\n left: " |
17 |
+ nLeft + "px;\n top: " + nTop + "px;"); |
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/
- JavaScript : Array assignment creates reference not copy
JavaScript : Array assignment creates reference not copy 29 May 2015 Consider we have an array var a ...
- JavaScript Event Loop和微任务、宏任务
为什么JavaScript是单线程? JavaScript的一大特点就是单线程, 同一时间只能做一件事情,主要和它的用途有关, JavaScript主要是控制和用户的交互以及操作DOM.注定它是单线程 ...
- javascript event loop
原文: https://blog.csdn.net/sjn0503/article/details/76087631 简单来讲,整体的js代码这个macrotask先执行,同步代码执行完后有micro ...
- JavaScript json loop item in array
Iterating through/Parsing JSON Object via JavaScript 解答1 Your JSON object is incorrect because it ha ...
- javaScript Event Loop + NodeJs问题解析
http://www.ruanyifeng.com/blog/2014/10/event-loop.html https://github.com/ElemeFE/node-interview/tre ...
- JavaScript event loop事件循环 macrotask与microtask
macrotask 姑且称为宏任务,在很多上下文也被简称为task.例如: setTimeout, setInterval, setImmediate, I/O, UI rendering. mic ...
- 深入理解 JavaScript 事件循环(一)— event loop
引言 相信所有学过 JavaScript 都知道它是一门单线程的语言,这也就意味着 JS 无法进行多线程编程,但是 JS 当中却有着无处不在的异步概念 .在初期许多人会把异步理解成类似多线程的编程模式 ...
- JavaScript事件循环(Event Loop)机制
JavaScript 是单线程单并发语言 什么是单线程 主程序只有一个线程,即同一时间片断内其只能执行单个任务. 为什么选择单线程? JavaScript的主要用途是与用户互动,以及操作DOM.这决定 ...
- JavaScript 事件循环 — event loop
引言 相信所有学过 JavaScript 都知道它是一门单线程的语言,这也就意味着 JS 无法进行多线程编程,但是 JS 当中却有着无处不在的异步概念 .在初期许多人会把异步理解成类似多线程的编程模式 ...
- JavaScript 风格指导(Airbnb版)
JavaScript 风格指导(Airbnb版) 用更合理的方式写 JavaScript 原文 翻译自 Airbnb JavaScript Style Guide . 目录 类型 引用 对象 数组 解 ...
随机推荐
- iOS: 学习笔记, 使用FMDatabase操作sqlite3
使用FMDatabase操作sqlite3数据库非常简单和方便 // // main.m // iOSDemo0602_sqlite3 // // Created by yao_yu on 14-6- ...
- 写了几天的博客-feel
写博客 真的总结我自己的知识.长见识了.记录下自己遇到的东西,算是一个总结,有问题了,还可以回头看一下.很好 真的很好.
- 轻量级表格插件Bootstrap Table。拥有强大的支持固定表头、单/复选、排序、分页、搜索及自定义表头等功能。
Bootstrap Table是轻量级的和功能丰富的以表格的形式显示的数据,支持单选,复选框,排序,分页,显示/隐藏列,固定标题滚动表,响应式设计,Ajax加载JSON数据,点击排序的列,卡片视图等. ...
- js将数字转换成大写的人民币表达式
function changeNumMoneyToChinese(money) { var cnNums = new Array("零", "壹", " ...
- Hibernate+jxl+excel导入数据库
在将excel中的10w行数据导入数据库中时,总发生内存溢出,一开始使用的Spring+Hibernate;不知如何使用批处理,后来只是用Hibernate,10W行数据几分钟完成, 代码如下: pu ...
- 如何在jasperreport自动生成序号
在导出报表时,有时候我们需要显示序号,有两种方法: 1.就是再加一个字段,就是说将序号也当做是要导出的字段来处理,然后用程序给这个字段赋值,这方面有点傻,就不说了. 2.利用jasperreport提 ...
- gitweb安装
gitweb安装: 1. 简介 Gitweb提供了git版本库的图形化web浏览功能.可以到网站http://git.kernel.org/体验下效果,如下图所示. Gitweb界面 它既可以通过配置 ...
- 【转】Java中如何遍历Map对象的4种方法
原文网址:http://blog.csdn.net/tjcyjd/article/details/11111401 在Java中如何遍历Map对象 How to Iterate Over a Map ...
- 字符串(后缀数组):HAOI2016 找相同子串
[HAOI2016]找相同子串 [题目描述] 给定两个字符串,求出在两个字符串中各取出一个子串使得这两个子串相同的方案数.两个方案不同当且仅当这两个子串中有一个位置不同. [输入格式] 两行,两个字符 ...
- 20140704笔试面试总结(java)
1.java数组定义 1.与其他高级语言不同,Java在数组声明时并不为数组分配存储空间,因此,在声明的[]中不能指出数组的长度 2.为数组分配空间的两种方法:数组初始化和使用new运算符 3.未分配 ...