for in

For in can get the attribute name of the object, but not the value of the attribute.

 const obj = {
     a: 1,
     b: 2,
     c: 3
 }

 const arr = [6, 7, 8];

 for (const key in obj) {
     console.log(key, 'key');
 }

 for (const key in arr) {
    console.log(key, 'key66');
 }

Copy the code

For in gets the property name on the prototype of the object, which is filtered by hasOwnProperty

const obj = { a: 1, b: 2, c: 3 }; function myObj() { this.d = 4; } myObj.prototype = obj; const testObj = new myObj(); for (const key in testObj) { console.log(key); } for (const key in testObj) { if (object.hasOwnProperty(key)) { console.log(key, 'key'); }}Copy the code

for of

For of returns an error when used for normal objects

const obj = { a: 1, b: 2, c: 3 };

for (const key of obj) {
   console.log(key, 'key');
}
Copy the code

For of can iterate over groups of numbers, array-like objects, strings, sets, maps, and Generator objects

const arr = [1, 2, 3]; for (const key of arr) { console.log(key, 'arr'); } const mapData = new Map([['a', 1], ['b', 2], ['c', 3]]); console.log(mapData, 'mapData'); for (const key of mapData) { console.log(key, 'map') } (function() { for (const key of arguments) { console.log(key, 'argument'); }}) (4 and 6)Copy the code

conclusion

for… In loops are designed primarily to iterate over objects, and can iterate over properties on prototypes, not over groups of numbers

for… The of loop can be used to iterate over groups of numbers, array-like objects, strings, sets, maps, and Generator objects