In English, the word Loop
refers to the shape created by a curved line. Similar concept, the word Loop
has been used in programming. If you look at the picture below, you will clearly understand how the flow of instructions is repeated in a loop of actions. In programming, the concept of loops is not a new concept, they are often used while coding. Although the syntax is different between languages, the basic concepts are the same, repeat the same code blocks as needed. JavaScript adds loop types (including various types of loops) and makes working with them more comfortable and efficient. In this article, we will learn about all the loops available in JavaScript.
Definition of Loop
In computer programming, Loop
is a process of repeating a specific block of code.
JavaScript loop types
There are seven loop types in JavaScript. We've listed them out to help you understand their workflow and usage more clearly. This article will also help you differentiate between these seven loop types, such as where, when, or how to use them. let's start.
while
Loop
while
Loops are one of the most basic types of loops available in JavaScript. You must have heard that JavaScript is not the only programming language. The
while
statement generates a loop that is executed in a specific block of statements if the condition is true
. The condition is checked every time before executing the code block.
Syntax
while (条件) { // 代码块}
Example
var i = 8;while (i < 10) { console.log('我小于10') i++ }
In the above example, the condition (i will be checked first, if the condition is <code>true
, the code block in while
will be executed, and before the next iteration, the value of i
will be increased by 1
, mainly It's because we have added a i++
statement.
do-while
Loop
do-while
is slightly different from while
because it contains an additional feature , executed at least once.
Syntax
do { // 代码块}while (条件)
Example
var i = 8;do { console.log('我的值是' + i) i++ }while (i > 7 && i < 10)
You can see that our condition is (i > 7 && i , but When <code>i=7
, the value has been printed. Because this looping technique first executes the code block without considering the condition, after the code block is executed, the condition is executed in the second round. For the second time the loop traverses the code block, only the condition will be executed if it is true
.
for
Loop
while
Loop and for
loop work exactly the same way, even the execution time is not too big difference. So, what is needed for another circulatory system that provides the same functionality?
In a for
loop, the loop variable declaration and initialization, conditional query and loop variable increment or decrement can all be completed in the same line. It increases readability and reduces the chance of errors.
Syntax
for ([变量初始化];[条件];[变量递增或递减]) { // 代码块 }
Example
for (var i = 0; i < 10; i++) { console.log('我的值是: ' + i) }
As shown in the above example, variable initialization i = 0
, condition i and the increment of the variable <code>i++
are declared on the same line. It's easier to understand and more readable, right? The use of
for
loop is exactly the same as the previously mentioned while
loop. But in order to make the code easier to read and understand, most of the time we use for
loops instead of while
loops.
forEach()
It is the prototype method of arrays (even map
and set
). The forEach()
method calls a given function (or callback function) with each element in the array each time according to the index order index
. Note that forEach()
does not run the given function on array elements that have no values.
Syntax
array.forEach(function(currentValue, index, array){ // 函数主体})
forEach()
The method takes a function as a parameter. This function consists of three parameters:
currentValue
: Saves the current value being processedindex
: Saves the index of the value in that specific arrayarray
: Saves the entire array
You You can use forEach()
to iterate over a set set
, or you can use it to iterate over a map map
.
Example
var array = [10, 20, "hi", , {}, function () {console.log('我是一个函数')}]array.forEach(function(item, index){ console.log('array [' + index + '] 是: '+ item) })
forEach()
The method traverses the array
array. If you are not using index index
, you can only use array.forEach(function(item){})
. The parameters can be used accordingly, but these three parameters are not required every time.
Using forEach()
makes it very simple for us to traverse the array. Don't worry about loop variables, conditions and anything else, it takes care of all the iteration.
forEach()
和for
的区别
你可以使用一个从0
开始到array.length
(该数组长度)简单的遍历一个数组。那么为什么还要提出不同的选择呢?
一个经验法则是,如果你可以选择使用原型方法,你就应该使用原型方法。因为,原型方法更清楚地知道对象,并对最佳方法进行了优化。下面这个示例能更好的来说明他们的区别之处:
var arr = []; arr[0]=0; arr[10]=10;for(var i=0; i<arr.length; i++){ console.log("I am for:" + i); } arr.forEach(function(){ console.log("I am forEach"); });
如果你运行上面的代码,你会发现for
打印了11
次,而forEach()
只打印了两次:
原因是,for
循环是一个简单的for
循环,对它的用途一无所知。它从0
到arr.length
。然而,当你使用forEach()
的时候,它知道arr
只有两个元素,虽然长度是10
。累此,它实际上只迭代了两次。
根据这个,如果你想在循环中跳过繁重的工作,迭代一个iterable
,你应该使用forEach()
。然而,仅仅迭代(相同数量的迭代)的迭代时间相对于for
循环来说是次要的。因为迭代性能更好。
map()
map
是数组的另一个原型方法。map()
方法将创建一个新的数组,该数组的返回值由一个给定的数组的函数执行生成。
语法
var newArray= oldArray.map(function (currentValue, index, array){ //Return element for the newArray});
map()
方法以函数作为参数,该函数有三个参数:
currentValue
: 在数组中处理的当前元素index
:数组中正在处理的当前元素的索引值array
:数组映射的调用
示例
var num = [1, 5, 10, 15];var doubles = num.map(function(x) { return x * 2; });
在上面的示例中,名为doubles
的新数组将输出doubles=[2, 10, 20, 30]
和num
数组仍旧是num=[1, 5, 10, 15]
。
for…in
这个方法主要是对象的迭代。for...in
在语句中迭代对象的可枚举属性。对于每个不同的属性,可以执行语句。
因为我们知道数组也是一种特殊的对象,所以不要认为数组不能用这个来进行迭代。
语法
for (variableName in object) { Block of code }
示例
var obj = {a: 1, b: 2, c: 3}; for (var prop in obj) { console.log('obj.'+prop+'='+obj[prop]); };
为什么在数组中使用for...in
迭代不可取?
for...in
不应该在数组迭代中使用,特别是index
顺序非常重要。
实际上,数组索引和一般对象属性之间没有区别,数组索引只是可枚举属性。
for...in
不会每次都以任何特定的顺序返回index
值。for...in
在迭代中,这个循环将返回所有可枚举属性,包括那些具有非整数名称的属性和继承的属性。
因此,建议在遍历数组时使用for
或forEach()
。因为迭代的顺序是依赖于现实的迭代,并且遍历一个数组,使用for...in
可能不会以一致的顺序访问元素。
var arr = []; arr[2] = 2; arr[3] = 3; arr[0] = 0; arr[1] = 1;
在这种情况下,使用forEach()
将输出一个0, 1, 2, 3
。但使用for...in
并不能保证会输出什么。
对于for...in
还有一件事你应该记住,它遍历对象的所有属性,包括继承的(来自父类)。如果只想在对象自己的属性上进行迭代,那么应该执行下面这样的操作:
for(var prop in obj){ if(obj.hasOwnProperty(prop)){ Code block here } }
for…of
这是ES6中新引入的一种循环类型。使用for...of
语句,你可以遍历任何可迭代的对象,比如Array
、String
、Map
、WeakMap
、Set
、参数对象、TypeArray
,甚至一般对象。
语法
for (variable of iterable) { Block of code }
示例
var str= 'paul';for (var value of str) { console.log(value); }
map的迭代
let itobj = new Map([['x', 0], ['y', 1], ['z', 2]]);for (let kv of itobj) { console.log(kv); }// => ['x', 0]// => ['y', 1]// => ['z', 2]for (let [key, value] of itobj) { console.log(value); }// => 0// => 1// => 2
for...in
循环主要遍历对象,其实际的插入顺序中是可枚举的属性;for...of
迭代任何可迭代对象的给定值(而不是属性名)。
Object.prototype.objProto = function() {}; Array.prototype.arrProto = function() {};let iterable = [8, 55, 9]; iterable.title = 'VoidCanvas';for (let x in iterable) { console.log(x); // logs 0, 1, 2, title, arrProto, objProto}for (let i of iterable) { console.log(i); // 8, 55, 9}
正如你所见,for...of
都是关于对象自己value
的迭代,而for...in
将会考虑原型和继承的属性。如果你想在对象上迭代(而不是迭代)。for...of
将会考虑它自己的所有属性,但迭代的情交下,它只会考虑适合这种迭代的元素。这就是为什么在上面的例子中,for...of
没有迭代属性。
相关推荐:
The above is the detailed content of Summary analysis of loop types in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment