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

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

    The for-in statement iterates over the enumerable properties of an object, in arbitrary order.

    The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype

    You can think of it as "for in" basically iterates and list out all the keys.

    var str = 'abc';
    var arrForOf = [];
    var arrForIn = [];
    
    for(value of str){
      arrForOf.push(value);
    }
    
    for(value in str){
      arrForIn.push(value);
    }
    
    console.log(arrForOf); 
    // ["a", "b", "c"]
    console.log(arrForIn); 
    // ["0", "1", "2", "formatUnicorn", "truncate", "splitOnLast", "contains"]
    

提交回复
热议问题