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

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

    The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. Enumerable properties are those properties whose internal [[Enumerable]] flag is set to true, hence if there is any enumerable property in the prototype chain, the for...in loop will iterate on those as well.

    The for...of statement iterates over data that iterable object defines to be iterated over.

    Example:

    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {};
    
    let iterable = [3, 5, 7];
    
    for (let i in iterable) {
      console.log(i); // logs: 0, 1, 2, "arrCustom", "objCustom"
    }
    
    for (let i in iterable) {
      if (iterable.hasOwnProperty(i)) {
        console.log(i); // logs: 0, 1, 2,
      }
    }
    
    for (let i of iterable) {
      console.log(i); // logs: 3, 5, 7
    }
    

    Like earlier, you can skip adding hasOwnProperty in for...of loops.

提交回复
热议问题