js几种循环的总结

209 阅读1分钟

1,forEach循环

const a = ["a","ss","cc"]

a.forEach(function(value , index , array){},thisValue) 
//value为遍历的当前元素
//index为当前索引
//array为正在操作的数组
//thisValue可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值。
//返回值为undefined

//常用写法
a.forEach(index =>{
// if (index ==='ss') {
// break;
// }   // 终止循环 如果终止循环会报错
    console.log(index)
})

不能跳过或者终止循环

2.map循环

a.map(function(currentValue,index,arr){}, thisValue)

和forEach的区别就是返回值为一个新的数组

3.for in 循环 返回可枚举的属性

for(i in a){
   console.log(a[i])
} //a ss cc 11   // 返回可枚举的属性

注意这里的i的类型是string

3.for循环

for(let i=0;i<a.length;i++){
    console.log(a[i])
}

5.for of 循环 es6用法 可终止循环

for(let index of a){
  if(index === 'ss'){
    continue  // break
  }
  console.log(index)
}//a ss cc

break完全结束循环,continue终止本次循环。for-of循环只会遍历自身的属性。