💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 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 迭代属性名称