The difference between for···in and for···of

The difference between for···in and for···of:

The first sentence: (for···in takes key, for··of takes value)
①From the perspective of traversing the array, for···in traverses the key (ie subscript), and for···of traverses What comes out is value (that is, the value of the array);

var arr = [99,88,66,77];
for(let i in arr){
    
    
    console.log(i);   //0,1,2,3
}
for(let i of arr){
    
    
    consoel.log(i);   //99,88,66,77
}

②From the perspective of traversing strings, it is the same as an array.
③From the perspective of traversing objects, for···in will traverse the key of the object, but for···of will directly report an error.

var obj = {
    
    name:"Bob",age:25};
for(var i in obj){
    
    
	console.log(i)  // name age
}
for(var i of obj){
    
    
	console.log(i)   //报错
}

④ If you want to use for...of to traverse ordinary objects, you need to use it with Object.keys().

var person={
    
    
    name:'coco',
    age:22,
    locate:{
    
    
        country:'China',
        city:'beijing',
    }
}
for(var key of Object.keys(person)){
    
    
    //使用Object.keys()方法获取对象key的数组
    console.log(key+": "+person[key]);//name: coco,age: 22,locate: [object Object]
}

Guess you like

Origin blog.csdn.net/weixin_43638968/article/details/109291957