-
循环数组
区别一:for in 和 for of 都可以循环数组,for in 输出的是数组的index下标,而for of 输出的是数组的每一项的值。
const arr = [1,2,3,4] // for ... in for (const key in arr){ console.log(key) // 输出 0,1,2,3 } // for ... of for (const key of arr){ console.log(key) // 输出 1,2,3,4 }
-
循环对象
区别二:for in 可以遍历对象,for of 不能遍历对象,只能遍历带有iterator接口的,例如Set,Map,String,Arrayconst list = [{ name: 'lx' }, { age: 23 }] for (const val of list) { console.log(val) // 输出{ name: 'lx' }, { age: 23 } for (const key in val) { console.log(val[key]) // 输出 lx,23 } }
-
数组对象
const list = [{ name: 'lx' }, { age: 23 }] for (const val of list) { console.log(val) // 输出{ name: 'lx' }, { age: 23 } for (const key in val) { console.log(val[key]) // 输出 lx,23 } }
总结:for in适合遍历对象,for of适合遍历数组。for in遍历的是数组的索引,对象的属性,以及原型链上的属性。