Table of Contents
Definition of Loop
JavaScript loop types
Syntax
Example
do-whileLoop
forLoop
forEach()
forEach()for的区别
map()
语法
示例
for…in
for…of
map的迭代
Home Web Front-end JS Tutorial Summary analysis of loop types in JavaScript

Summary analysis of loop types in JavaScript

Feb 22, 2018 pm 02:24 PM
javascript js analyze

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.

whileLoop

whileLoops 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 (条件) {    // 代码块}
Copy after login

Example

var i = 8;while (i < 10) {
    console.log(&#39;我小于10&#39;)
    i++
}
Copy after login

In the above example, the condition (i < 10) will be checked first, if the condition is 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-whileLoop

do-while is slightly different from while because it contains an additional feature , executed at least once.

Syntax

do {    // 代码块}while (条件)
Copy after login

Example

var i = 8;do {
    console.log(&#39;我的值是&#39; + i)
    i++
}while (i > 7 && i < 10)
Copy after login

You can see that our condition is (i > 7 && i < 10), but When 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.

forLoop

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 ([变量初始化];[条件];[变量递增或递减]) {    // 代码块
}
Copy after login

Example

for (var i = 0; i  < 10; i++) {
    console.log(&#39;我的值是: &#39; + i)
}
Copy after login

As shown in the above example, variable initialization i = 0, condition i < 10 and the increment of the variable 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){    // 函数主体})
Copy after login

forEach()The method takes a function as a parameter. This function consists of three parameters:

  • currentValue: Saves the current value being processed

  • index : Saves the index of the value in that specific array

  • array: 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(&#39;我是一个函数&#39;)}]array.forEach(function(item, index){
    console.log(&#39;array [&#39; + index + &#39;] 是: &#39;+ item)
})
Copy after login

Summary analysis of loop types in JavaScript

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");
});
Copy after login

如果你运行上面的代码,你会发现for打印了11次,而forEach()只打印了两次:

Summary analysis of loop types in JavaScript

原因是,for循环是一个简单的for循环,对它的用途一无所知。它从0arr.length。然而,当你使用forEach()的时候,它知道arr只有两个元素,虽然长度是10。累此,它实际上只迭代了两次。

根据这个,如果你想在循环中跳过繁重的工作,迭代一个iterable,你应该使用forEach()。然而,仅仅迭代(相同数量的迭代)的迭代时间相对于for循环来说是次要的。因为迭代性能更好。

map()

map是数组的另一个原型方法。map()方法将创建一个新的数组,该数组的返回值由一个给定的数组的函数执行生成。

语法

var newArray= oldArray.map(function (currentValue, index, array){    //Return element for the newArray});
Copy after login

map()方法以函数作为参数,该函数有三个参数:

  • currentValue: 在数组中处理的当前元素

  • index:数组中正在处理的当前元素的索引值

  • array:数组映射的调用

示例

var num = [1, 5, 10, 15];var doubles = num.map(function(x) {    return x * 2;
});
Copy after login

Summary analysis of loop types in JavaScript

在上面的示例中,名为doubles的新数组将输出doubles=[2, 10, 20, 30]num数组仍旧是num=[1, 5, 10, 15]

for…in

这个方法主要是对象的迭代。for...in在语句中迭代对象的可枚举属性。对于每个不同的属性,可以执行语句。

因为我们知道数组也是一种特殊的对象,所以不要认为数组不能用这个来进行迭代。

语法

for (variableName in object) {
    Block of code
}
Copy after login

示例

var obj = {a: 1, b: 2, c: 3};    
for (var prop in obj) {
    console.log(&#39;obj.&#39;+prop+&#39;=&#39;+obj[prop]);
};
Copy after login

为什么在数组中使用for...in迭代不可取?

for...in不应该在数组迭代中使用,特别是index顺序非常重要。

实际上,数组索引和一般对象属性之间没有区别,数组索引只是可枚举属性。

for...in不会每次都以任何特定的顺序返回index值。for...in在迭代中,这个循环将返回所有可枚举属性,包括那些具有非整数名称的属性和继承的属性。

因此,建议在遍历数组时使用forforEach()。因为迭代的顺序是依赖于现实的迭代,并且遍历一个数组,使用for...in可能不会以一致的顺序访问元素。

var arr = [];
arr[2] = 2;
arr[3] = 3;
arr[0] = 0;
arr[1] = 1;
Copy after login

在这种情况下,使用forEach()将输出一个0, 1, 2, 3。但使用for...in并不能保证会输出什么。

对于for...in还有一件事你应该记住,它遍历对象的所有属性,包括继承的(来自父类)。如果只想在对象自己的属性上进行迭代,那么应该执行下面这样的操作:

for(var prop in obj){    if(obj.hasOwnProperty(prop)){
        Code block here
    }
}
Copy after login

for…of

这是ES6中新引入的一种循环类型。使用for...of语句,你可以遍历任何可迭代的对象,比如ArrayStringMapWeakMapSet、参数对象、TypeArray,甚至一般对象。

语法

for (variable of iterable) {
    Block of code
}
Copy after login

示例

var str= &#39;paul&#39;;for (var value of str) {
    console.log(value);
}
Copy after login

Summary analysis of loop types in JavaScript

map的迭代

let itobj = new Map([[&#39;x&#39;, 0], [&#39;y&#39;, 1], [&#39;z&#39;, 2]]);for (let kv of itobj) {
    console.log(kv);
}// => [&#39;x&#39;, 0]// => [&#39;y&#39;, 1]// => [&#39;z&#39;, 2]for (let [key, value] of itobj) {
    console.log(value);
}// => 0// => 1// => 2
Copy after login

for...in循环主要遍历对象,其实际的插入顺序中是可枚举的属性;for...of迭代任何可迭代对象的给定值(而不是属性名)。

Object.prototype.objProto = function() {}; 
Array.prototype.arrProto = function() {};let iterable = [8, 55, 9];
iterable.title = &#39;VoidCanvas&#39;;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}
Copy after login

正如你所见,for...of都是关于对象自己value的迭代,而for...in将会考虑原型和继承的属性。如果你想在对象上迭代(而不是迭代)。for...of将会考虑它自己的所有属性,但迭代的情交下,它只会考虑适合这种迭代的元素。这就是为什么在上面的例子中,for...of没有迭代属性。

相关推荐:

JS realizes text intermittent cycle scrolling

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analyze the advantages and disadvantages of static positioning technology Analyze the advantages and disadvantages of static positioning technology Jan 18, 2024 am 11:16 AM

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,

See all articles