Home >Web Front-end >JS Tutorial >Detailed explanation of different usage codes of for loop statements in javascript

Detailed explanation of different usage codes of for loop statements in javascript

伊谢尔伦
伊谢尔伦Original
2017-07-26 17:42:351556browse

Loop statements are often used in program implementation, among which the for loop is found in most languages. In JavaScript, there are several different uses of for loops. Here are my understandings of each.

The first type: (Normally, perform related operations in a loop)

var objA=document.getElementsByTagName("a"); 
var i,max; 
for(i=0,max=objA.length;i<max;i++){ 
objA[i].onclick=function(){ 
alert(this.innerHTML); 
} 
}

Loop, register the click operation of the hyperlink label in sequence

The second type: (for objects, operating object content)

var person={name:&#39;wmhello&#39;,age:&#39;28&#39;}; 
var tips=&#39;&#39;; for(var obj in person){ 
tips+=obj+&#39;-->&#39;+person[obj]+&#39;\n&#39; 
} 
alert(tips)

The third type: (often used for arrays, performing specific operations on arrays)

var num=[1,3,5]; 
var total=0; 
num.forEach(function(e){ 
total+=e; 
}); 
alert(total);

This forEach loop works in firefox and chrome

The above is the detailed content of Detailed explanation of different usage codes of for loop statements 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