区别:
| 区别 | for of | for in |
|---|---|---|
| 数组 | 值 | 索引 |
| 对象 | \ | 键 |
-
for in可以遍历数组,也可以遍历对象-
遍历
数组拿到的是索引let arr=['a','b','c','d','e'] for(let i in arr){ console.log(i)//索引0,1,2,3,4 console.log(arr[i])//值a,b,c,d,e } -
遍历
对象拿到的是键let obj={name:'张三',age:18} for(let i in obj){ console.log(i)//键 name,age console.log(obj[i])//值 张三,18 }
-
-
for of只能遍历数组,拿到的是值
for(let i of arr){
console.log(i)//值a,b,c,d,e
}