What is the difference between ( for… in ) and ( for… of ) statements in JavaScript?

前端 未结 14 1457
慢半拍i
慢半拍i 2020-11-22 06:22

I know what is for... in loop (it iterates over key), but heard the first time about for... of (it iterates over value).

I am confused with

14条回答
  •  余生分开走
    2020-11-22 06:33

    I find a complete answer at : https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html (Although it is for type script, this is same for javascript too)

    Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

    Here is an example that demonstrates this distinction:

    let list = [4, 5, 6];
    
    for (let i in list) {
       console.log(i); // "0", "1", "2",
    }
    
    for (let i of list) {
       console.log(i); // "4", "5", "6"
    }
    

    Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

    let pets = new Set(["Cat", "Dog", "Hamster"]);
    pets["species"] = "mammals";
    
    for (let pet in pets) {
       console.log(pet); // "species"
    }
    
    for (let pet of pets) {
        console.log(pet); // "Cat", "Dog", "Hamster"
    }
    

提交回复
热议问题