for in和for of的区别

1.循环数组
区别一:for in 和 for of 都可以循环数组,for in 输出的是数组的index下标,而for of 输出的是数组的每一项的值。

const arr = ['a', 'b', 'c', 'd']
 
// for ... in
for (const key in arr) {
  console.log(key) // 输出 0,1,2,3
}
 
// for ... of
for (const key of arr) {
  console.log(key) // 输出 a,b,c,d
}

2.循环对象

区别二:for in 可以遍历对象,for of 不能遍历对象,只能遍历带有iterator(迭代器)接口的,例如Set,Map,String,Array

const object = { name: 'zs', age: 23 }
// for ... in
for (const key in object) {
  console.log(key) // 输出 name,age
  console.log(object[key]) // 输出 zs,23
}
// for ... of
for (const key of object) {
  console.log(key) // 报错 Uncaught TypeError: object is not iterable
}

3.数组对象

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
    }
  }

else:
1.作用于数组的for-in循环除了遍历数组元素以外,还会遍历自定义属性,举个例子,如果你的数组中有一个可枚举的类型a.name,那么循环将额外执行一次,遍历到名为name的索引,甚至数组原型链上的属性都能被访问到,此时如果你不希望得到他们,就应该结在for-in循环的时候添加 hasOwnProperty()方法来过滤掉非自有属性。
2.index索引为字符串型数字,不能直接进行几何运算
3.遍历顺序有可能不是按照实际数组的内部顺序
4.使用for in会遍历数组所有的可枚举属性,包括原型。例如原型方法method和name属性

var a = ["a", "b", "c"];
for(var index in a){
//   console.log(a[index]);
  console.log(typeof index);  //string
}

var b = new Array(1,2,3,4)    //创建一个数组
b.name = '小明'               //给数组添加一个属性
Array.prototype.age = 12      //给数组的原型也添加一个属性 
for(let key in b){
  console.log(key)
}

//output 
0
1
2
3
name
age

//同样用for of 遍历结果如下
for(let value of b){
  console.log(value)
}
//output
1
2
3
4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值