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:'wmhello',age:'28'}; var tips=''; for(var obj in person){ tips+=obj+'-->'+person[obj]+'\n' } 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!