[Notes] The difference between for...of and for...in

What is for...of?

for...of is a new traversal method in ES6, which allows traversing a data structure (array, object, etc.) containing an iterator interface and returning the value of each item.

The difference between for...of and for...in in ES3

  • for...of traverses to obtain the key value of the object, and for...in obtains the key name of the object;

  • for... in will traverse the entire prototype chain of the object, the performance is very poor and it is not recommended to use it, while for... of only traverses the current object and does not traverse the prototype chain;

  • For array traversal, for...in will return all enumerable properties in the array (including enumerable properties on the prototype chain), and for...of will only return the property values ​​corresponding to the subscripts of the array;

Summary: The for...in loop is mainly for traversing objects, not for traversing arrays; the for...of loop can be used for traversing arrays, array-like objects, strings, Sets, Maps, and Generator objects.

How to use for...of?

for...of is a new traversal method in ES6, which allows traversal of a data structure (array, object, string, etc.) containing an iterator interface and returns the value of each item. Traversing ordinary objects with for..of will report an error .

1. If the object to be traversed is an array-like object, use Array.from to convert it into an array.

var obj = {
    0:'one',
    1:'two',
    length: 2
};
obj = Array.from(obj);
for(var k of obj){
    console.log(k)
}
  1. If it is not an array-like object, just add a [Symbol.iterator] attribute to the object and point to an iterator.

var obj = {
    a:1,
    b:2,
    c:3
};
obj[Symbol.iterator] = function(){
var keys = Object.keys(this);
var count = 0;
return {
            next(){
                if(count<keys.length){
                    return {value: obj[keys[count++]],done:false};
                }else{
                    return {value:undefined,done:true};
                }
        }
    }
};

for(var k of obj){
    console.log(k);
}
 
 

TIPS:

  • for...of is used to traverse the value of iterrable, and for...in is used to traverse the keys of objects.

  • for...of cannot be used to traverse objects, for...in can traverse iterable arrays and strings, but should avoid using it to traverse iterable objects.

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129078179