for in与for of | 青训营

50 阅读1分钟

for in与for of

​ 对数组的遍历大家最常用的就是for循环,ES5的话也可以使用forEach,ES5具有遍历数组功能的还有map、filter、some、every、reduce、reduceRight等

​ 但是使用foreach遍历数组的话,使用break不能中断循环,使用return也不能返回到外层函数。

for in 与 for of

遍历对象

  
  const obj = { a: 1, b: 2, c: 3 }
  for (let i in obj) {
      console.log(i)
      // a
      // b
      // c
  }
  for (let i of obj) {
      console.log(i)
      // obj is not iterable
  }

遍历数组

  
  const arr = ['a', 'b', 'c']
  for (let i in arr) {
      console.log(i)
      // 0
      // 1
      // 2
  }
  for (let i of arr) {
      console.log(i)
      // a
      // b
      // c
  }

for in返回的是数组的下标

for of返回的是a b c

遍历数组并添加属性

  const arr = ['a', 'b']
  // 手动给 arr数组添加一个属性
  arr.name = 'qiqingfu'// for in 循环可以遍历出 name 这个键名
  for (let i in arr) {
      console.log(i)
      // a
      // b
      // name
  }

总结:

for in适合遍历对象,for of适合遍历数组

for in

  • for ... in 循环返回的值都是数据结构的键值名
  • 遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)。
  • for ... in 循环不仅可以遍历数字键名,还会遍历原型上的值和手动添加的其他键
  • 特别情况下,for ... in 循环会以看起来任意的顺序遍历键名

for of

  • for of 循环用来获取一对键值对中的值,而 for in 获取的是键名

  • for of 不同与 forEach,它可以与 break、continue和return 配合使用,也就是说 for of 循环可以随时退出循环

  • 提供了遍历所有数据结构的统一接口

参考:

前端阳光 zhuanlan.zhihu.com/p/161892289

yolanda_筱筱 juejin.cn/post/684490…