javascript中for迴圈有幾種不同的使用方式介紹

來源:互聯網
上載者:User

 for迴圈是多數語言都有的。在javascript中,for迴圈有幾種不同的使用方式,下面為大家一一介紹下

程式實現中經常要用到迴圈語句,其中for迴圈是多數語言都有的。在javascript中,for迴圈有幾種不同的使用方式,下面就分別來講述我的理解。 

 

第一種:(通常情況,迴圈執行相關操作) 

 代碼如下:

var objA=document.getElementsByTagName("a"); 

var i,max; 

for(i=0,max=objA.length;i<max;i++){ 

objA[i].onclick=function(){ 

alert(this.innerHTML); 

} 

 

} 

 

迴圈,依次註冊超連結標籤的單擊操作 

 

第二種:(針對對象,操作對象內容) 

代碼如下:

var person={name:'wmhello',age:'28'}; 

var tips=''; for(var obj in person){ 

tips+=obj+'-->'+person[obj]+'\n' 

 

} 

 

alert(tips) 

 

第三種:(常用於數組,對數組執行特定的操作) 

代碼如下:

var num=[1,3,5]; 

var total=0; 

num.forEach(function(e){ 

total+=e; 

}); 

alert(total); 

 

此forEach迴圈在firefox和chrome中有效 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.