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

前端 未结 14 1463
慢半拍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:30

    Another difference between the two loops, which nobody has mentioned before:

    Destructuring for...in is deprecated. Use for...of instead.

    Source

    So if we want to use destructuring in a loop, for get both index and value of each array element, we should to use the for...of loop with the Array method entries():

    for (const [idx, el] of arr.entries()) {
        console.log( idx + ': ' + el );
    }
    

提交回复
热议问题