JavaScript的幾種循環方式


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

目錄:

  • for
  • forEach
  • do...while
  • while
  • for...in
  • for...of
  • for...in vs for...of

介紹

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 迭代屬性名稱
原文地址:https://segmentfault.com/a/1190000016110909


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM