js几种for循环的几种用法

JavaScript07

js几种for循环的几种用法,第1张

第一种:普通for循环

for(j = 0 j < arr.length j++) {

   

}

第二种:优化版for循环

for(j = 0,len=arr.length j < len j++) {

   

}

第三种:弱化版for循环

for(j = 0 arr[j]!=null j++) {

   

}

第四种:foreach循环

arr.forEach(function(e){  

   

})

第五种:foreach变种

Array.prototype.forEach.call(arr,function(el){  

   

})

第六种:for in循环

for(j in arr) {

   

}

第七种:map遍历

arr.map(function(n){  

   

})

第八种:forof遍历(需要ES6支持)

for(let value of arr) {  

   

})

for in 是ES5语法,遍历对象的枚举属性,可以简单理解成对象的key

for of是ES6语法,遍历实现iterator接口的成员,可以简单理解成for of只可以循环可迭代对象的可迭代属性,不可迭代属性在循环中被忽略了

Object.prototype.objCustom = function () {} 

Array.prototype.arrCustom = function () {}

let iterable = [3, 5, 7]

iterable.foo = "hello"

for (let i in iterable) {

  console.log(i) // logs 0, 1, 2, "foo", "arrCustom", "objCustom"

}

for (let i of iterable) {

  console.log(i) // logs 3, 5, 7

}