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

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

    Everybody did explain why this problem occurs, but it's still very easy to forget about it and then scratching your head why you got wrong results. Especially when you're working on big sets of data when the results seem to be fine at first glance.

    Using Object.entries you ensure to go trough all properties:

    var arr = [3, 5, 7];
    arr.foo = "hello";
    
    for ( var [key, val] of Object.entries( arr ) ) {
       console.log( val );
    }
    
    /* Result:
    
    3
    5
    7
    hello
    
    */
    
    0 讨论(0)
  • 2020-11-22 06:46

    Here is a useful mnemonic for remembering the difference between for...in Loop and for...of Loop.

    "index in, object of"

    for...in Loop => iterates over the index in the array.

    for...of Loop => iterates over the object of objects.

    0 讨论(0)
提交回复
热议问题