Home  >  Article  >  Web Front-end  >  Summary analysis of loop types in JavaScript

Summary analysis of loop types in JavaScript

小云云
小云云Original
2018-02-22 14:24:411578browse

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

Example

var i = 8;while (i < 10) {
    console.log(&#39;我小于10&#39;)
    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-whileLoop

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(&#39;我的值是&#39; + 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.

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

Example

for (var i = 0; i  < 10; i++) {
    console.log(&#39;我的值是: &#39; + 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 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)
})

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

如果你运行上面的代码,你会发现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});

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

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

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

  • array:数组映射的调用

示例

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

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
}

示例

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

为什么在数组中使用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;

在这种情况下,使用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语句,你可以遍历任何可迭代的对象,比如ArrayStringMapWeakMapSet、参数对象、TypeArray,甚至一般对象。

语法

for (variable of iterable) {
    Block of code
}

示例

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

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

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}

正如你所见,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:
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
Previous article:10 common js functionsNext article:10 common js functions