您现在的位置是:首页 > 文章详情

JavaScript的几种循环方式

日期:2018-10-07点击:360

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

原文链接:https://yq.aliyun.com/articles/672937
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章