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

前端 未结 14 1295
慢半拍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
    
    */
    

提交回复
热议问题