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.
In computer programming, Loop
is a process of repeating a specific block of code.
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
Loopwhile
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.
while (条件) { // 代码块}
var i = 8;while (i < 10) { console.log('我小于10') i++ }
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-while
Loopdo-while
is slightly different from while
because it contains an additional feature , executed at least once.
do { // 代码块}while (条件)
var i = 8;do { console.log('我的值是' + i) i++ }while (i > 7 && i < 10)
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
.
for
Loopwhile
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.
for ([变量初始化];[条件];[变量递增或递减]) { // 代码块 }
for (var i = 0; i < 10; i++) { console.log('我的值是: ' + i) }
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.
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
.
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 (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 } }
这是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); }
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!