for of 和 for in 的区别

  • 1.共性
  • 2.区别
    • 1.两者对比例子(遍历对象)
    • 2.两者对比例子(遍历数组)
  • 3.特点
    • ①. ``for in`` 特点
    • ①. ``for of`` 特点

1.共性

for offor in都是用来遍历的属性

2.区别

  1. for...in 语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。
  2. for in得到对对象的key或数组,字符串的下标
  3. for offorEach一样,是直接得到值
  4. for of不能用于对象

1.两者对比例子(遍历对象)

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)    //输出: Uncaught TypeError: obj is not iterable 报错了
    }

说明: for infor of 对一个obj对象进行遍历,for in 正常的获取了对象的 key值,分别打印 a、b、c,而 for of却报错了。

2.两者对比例子(遍历数组)

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

3.特点

①. for in 特点

  • for … in 循环返回的值都是数据结构的 键值名(即下标)。
  • 遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)。
  • for … in 循环不仅可以遍历数字键名,还会遍历原型上的值和手动添加的其他键。
  • 特别情况下, for … in 循环会以看起来任意的顺序遍历键名
  • for in 的 常规属性排序属性
    在ECMAScript规范中定义了 「数字属性应该按照索引值⼤⼩升序排列,字符串属性根据创建时的顺序升序排列。」在这⾥我们把对象中的数字属性称为 「排序属性」,在V8中被称为 elements,字符串属性就被称为 「常规属性」, 在V8中被称为 properties。
function Foo() {
 this[100] = 'test-100'
 this[1] = 'test-1'
 this["B"] = 'bar-B'
 this[50] = 'test-50'
 this[9] = 'test-9'
 this[8] = 'test-8'
 this[3] = 'test-3'
 this[5] = 'test-5'
 this["A"] = 'bar-A'
 this["C"] = 'bar-C'
}
var bar = new Foo()
for(key in bar){
 console.log(`index:${key} value:${bar[key]}`)
}
//输出:
index:1 value:test-1
index:3 value:test-3
index:5 value:test-5
index:8 value:test-8
index:9 value:test-9
index:50 value:test-50
index:100 value:test-100
index:B value:bar-B
index:A value:bar-A
index:C value:bar-C

总结一句: for in 循环特别适合遍历对象。

①. for of 特点

  • for of 循环用来获取一对键值对中的值,而 for in 获取的是 键名
  • 一个数据结构只要部署了 Symbol.iterator 属性, 就被视为具有 iterator接口, 就可以使用 for of循环。
  • for of 不同与 forEach, 它可以与 break、continue和return 配合使用,也就是说 for of 循环可以随时退出循环。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。