Loop statements are often used in program implementation, among which for loops are available in most languages. In JavaScript, there are several different usage situations for loops. Let me explain my understanding separately below.
The first type: (usually, the loop performs related operations)
The code copy is as follows:
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 and register the click operation of the hyperlink tag in turn
The second type: (for objects, operate object content)
The code copy is as follows:
var person={name:'wmhello',age:'28'};
var tips=''; for(var obj in person){
tips+=obj+'-->'+person[obj]+'/n'
}
alert(tips)
The third type: (commonly used for arrays, performing specific operations on arrays)
The code copy is as follows:
var num=[1,3,5];
var total=0;
num.forEach(function(e){
total+=e;
});
alert(total);
This forEach loop works in firefox and chrome