JavaScript循环的写法有哪些

藏色散人
藏色散人 原创
2021-10-26 14:57:05 2068浏览

JavaScript循环的写法有:1、“for (let index = 0; index < len; index++) {...}”方式;2、“myArray.forEach(function(index){...}”方式等等。

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

JavaScript循环的写法有哪些?

javascript之for循环的几种写法

背景

javascript中的for循环选择多种多样,可你知道其中的差别在哪里吗?什么时候又该用哪种循环才是最佳策略?以上这些是本文想讨论的,欢迎交流。

说明

1、20年前的for循环

//20年前的写法
let len = myArray.Length
for (let index = 0; index < len; index++) {
  console.log(myArray[index])
}

中规中矩。

2、forEach

//ES5的写法
myArray.forEach(function(index){
    //操作你的index,index即为数组中的元素
})

缺点,没有返回值。

3、for...in

//ES5的写法,劝你慎重
for (let index in myArray) { 
  // 千万别这样做
  console.log(myArray[index]);
}

最糟糕的做法,因为此时的index是字符串,而且不一定按照数组的顺序输出,很吓人。

仅适用于遍历普通对象的key。

4、for...of

/**ES6写法
*支持数组
*类数组对象(如:NodeList对象)
*字符串
*Map
*set
*/
for (let value of myArray) {
  console.log(value);
}

【推荐学习:javascript基础教程

以上就是JavaScript循环的写法有哪些的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。