The difference between for in and for of

When traversing arrays or objects, we often use two methods: for in and for of,

Then the difference between these two methods is that both of them can be used for traversal,

But for in traverses the index of the array (index),

And for of traverses the array element value (value)

for in is more suitable for traversing objects, and of course it can also traverse arrays, but there will be some problems.

for in can traverse objects, for of cannot traverse objects, it can only traverse objects with iterator interface, such as Set,Map,String,Array

Difference 1: both for in and for of can loop the array, for in outputs the index subscript of the array, and for of outputs the value of each item of the array.

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

Difference 2: for in can traverse objects, while for of cannot traverse objects, but can only traverse objects with iterator interface, such as Set, Map, String, Array

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

array object

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

for in is suitable for traversing objects, and for of is suitable for traversing arrays. for in traverses the index of the array, the properties of the object, and the properties on the prototype chain.

Guess you like

Origin blog.csdn.net/yjxkq99/article/details/126961512