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

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

    A see a lot of good answers, but I decide to put my 5 cents just to have good example:

    For in loop

    iterates over all enumerable props

    let nodes = document.documentElement.childNodes;
    
    for (var key in nodes) {
      console.log( key );
    }

    For of loop

    iterates over all iterable values

    let nodes = document.documentElement.childNodes;
    
    for (var node of nodes) {
      console.log( node.toString() );
    }

提交回复
热议问题