首頁 > web前端 > js教程 > js中幾種不同迴圈的介紹(附程式碼)

js中幾種不同迴圈的介紹(附程式碼)

不言
發布: 2018-08-27 11:34:36
原創
1684 人瀏覽過

這篇文章帶給大家的內容是關於js中幾種不同循環的介紹(附程式碼) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

JavaScript提供了許多迭代迴圈的方法。

for

1

2

3

4

5

const list = ['a', 'b', 'c']

for (let i = 0; i < list.length; i++) {

  console.log(list[i]) //value

  console.log(i) //index

}

登入後複製
  • 您可以使用break中斷for迴圈

  • 您可以使用continue繼續for迴圈的下一個迭代

forEach

在ES5中引入。給定一個數組,您可以使用list.forEach()迭代其屬性:

1

2

3

4

5

6

7

8

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

list.forEach((item, index) => {

  console.log(item) //value

  console.log(index) //index

})

 

//index is optional

list.forEach(item => console.log(item))

登入後複製
不過需要注意的是您無法擺脫這個循環。

do...while

1

2

3

4

5

6

7

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

let i = 0

do {

  console.log(list[i]) //value

  console.log(i) //index

  i = i + 1

} while (i < list.length)

登入後複製

您可以使用break中斷while循環:

1

2

3

do {

  if (something) break

} while (true)

登入後複製

你可以使用continue跳到下一個迭代:

1

2

3

4

5

do {

  if (something) continue

 

  //do something else

} while (true)

登入後複製

while

1

2

3

4

5

6

7

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

let i = 0

while (i < list.length) {

  console.log(list[i]) //value

  console.log(i) //index

  i = i + 1

}

登入後複製

您可以使用break中斷while循環:

1

2

3

while (true) {

  if (something) break

}

登入後複製

你可以使用continue跳到下一個迭代:

1

2

3

4

5

while (true) {

  if (something) continue

 

  //do something else

}

登入後複製

與do...while的差別在於do. ..while總是至少執行一次迴圈。

for...in

迭代物件的所有可枚舉屬性,給出屬性名稱。

1

2

3

4

for (let property in object) {

  console.log(property) //property name

  console.log(object[property]) //property value

}

登入後複製

for...of

ES2015引入了for循環,它結合了forEach的簡潔性和破解能力:

1

2

3

4

5

6

7

8

9

10

//iterate over the value

for (const value of [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]) {

  console.log(value) //value

}

 

//get the index as well, using `entries()`

for (const [index, value] of [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;].entries()) {

  console.log(index) //index

  console.log(value) //value

}

登入後複製

注意使用const。此循環在每次迭代中創建一個新範圍,因此我們可以安全地使用它而不是let。

for...in VS FOR...OF

與for...in的差別在於:

  • for...of迭代屬性值

  • for...in 迭代屬性名稱

相關推薦:

#JS的for while迴圈

js的for in迴圈和java裡foreach迴圈的區別分析

以上是js中幾種不同迴圈的介紹(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板