JavaScript的循環方式(1)

JavaScript提供了許多通過LOOPS迭代的方法。本教程解釋了現代JAVASCRIPT中各種各樣的循環可能性

JavaScript提供了許多迭代循環的方法。本教程通過一個小例子和主要屬性解釋每一個。

for

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()迭代其屬性:

const list = ['a', 'b', 'c']
list.forEach((item, index) => {
  console.log(item) //value
  console.log(index) //index
})

//index is optional
list.forEach(item => console.log(item))

不過需要注意的是你無法擺脫這個循環。
do...while


const list = ['a', 'b', 'c']
let i = 0
do {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
} while (i < list.length)

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

do {
  if (something) break
} while (true)
你可以使用continue跳轉到下一個迭代:

do {
  if (something) continue

  //do something else
} while (true)
while
const list = ['a', 'b', 'c']
let i = 0
while (i < list.length) {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
}

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

while (true) {
  if (something) break
}
你可以使用continue跳轉到下一個迭代:

while (true) {
  if (something) continue

  //do something else
}

與do...while的區別在於do...while總是至少執行一次循環。

for...in
迭代對象的所有可枚舉屬性,給出屬性名稱。

for (let property in object) {
  console.log(property) //property name
  console.log(object[property]) //property value
}

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

//iterate over the value
for (const value of ['a', 'b', 'c']) {
  console.log(value) //value
}

//get the index as well, using `entries()`
for (const [index, value] of ['a', 'b', 'c'].entries()) {
  console.log(index) //index
  console.log(value) //value
}

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

for...in VS FOR...OF
與for...in的區別在於:

for...of 迭代屬性值
for...in 迭代屬性名稱

在這裏給大家分享一下,我是一名5年前端工程師,自己建了一個q羣:731771211 ,羣裏不停更新最新的教程和學習方法,加入一起學習與交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章