for...in 和 for...of的区别

116 阅读2分钟

最近刷面经的时候发现,平常很常用的for...in for...of,这两者很容易用着用习惯了,但容易疏忽两者的差别,于是决定梳理一下

image.png

循环数组

for...of:输出的是数组的每一项的。 for in: 输出的是数组的index下标

const arr = [1,2,5,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,5,4
    }

循环对象

for...in:输出的是对象的key,数组的索引原型链上的属性
for...of: 不能遍历对象,可以遍历数组对象,只能遍历带iterator接口的(如Set,Map,String,Array)。 for...of:

    // for ... of
    // 1.遍历带iterator接口的
    const arr = new Set([3, 4, 5, 6, 8]);
     for (const value of arr) {
         console.log(value); // 输出 3, 4, 5, 6, 8
     }
    // 2. 遍历数组对象
    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
      }
    }
    // 3.遍历对象报错
    for (const key of object) {
      console.log(key) // 报错 Uncaught TypeError: object is not iterable
    }   

补充:由于for...in会遍历原型链上的属性,所以在遍历对象的时候,如果不想同时遍历原型链上的属性,可以加一个条件判断:利用hasOwnProperty。

// 定义一个对象,包含自身属性和原型链上的属性
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayHello = function () {
    console.log('Hello, I am ' + this.name);
};

const person1 = new Person('Alice', 30);

// 测试用例
for (let key in person1) {
    if (person1.hasOwnProperty(key)) {
        console.log(key + ': ' + person1[key]); //name: Alice age: 30
    }
}

for (let key in person1) {
    console.log(key + ': ' + person1[key]); //name: Alice age: 30 sayHello: function () {console.log('Hello, I am ' + this.name);}
}

补充:遍历器(Iterator)见遍历器(Iterator)一文

for...in:

   const object = { name: 'lx', age: 23 }
    // for ... in
   // 1.遍历对象
    for (const key in object) {
      console.log(key) // 输出 name,age,对象的key
      console.log(object[key]) // 输出 lx,23
    }
    // for ... in
   // 2.遍历数组
   const arr = [3,4,5,6,8]
    for (const key in arr) {
      console.log(key) // 输出0,1,2,3,4,数组索引
      console.log(arr[key]) // 输出3,4,5,6,8
    } 

总结:

遍历数组:
for...of: 输出的是数组的每一项的
for in: 输出的是数组的index下标
遍历对象:
for...in: 输出的是对象key,数组的索引原型链上的属性
for...of: 不能遍历对象,可以遍历数组对象,只能遍历带iterator接口的(如Set,Map,String,Array)。