zoukankan      html  css  js  c++  java
  • [Javascript] Use JavaScript's for-in Loop on Objects with Prototypes

    Loops can behave differently when objects have chained prototype objects. Let's see the difference we get when we use the for-in loop on an object without a prototype, as opposed to an object with a prototype object.

    Let's say you have an object:

    const obj = {
      firstName: "Bar",
      lastName: "Foo"
    };

    Once you use for in loop:

    for (let property in obj) {
        console.log(property); // firstName, lastName
        n++;    
    }
    console.log(n); // 2

    We can add one prototype prop to the obj:

    const protoObj = {
      hair: "Brown"
    };
    
    Object.setPrototypeOf(obj, protoObj);

    On the prototype chain we have 'hair' prop.

    Now, if you use for in loop again:

    for (let property in obj) {
    
        console.log(property); //firstName, lastName, hair
        n++;
      
    }
    console.log(n); // 3

    Be to notice, 'hair' is on the prototype chain,is not on obj's own property, so if we want to fileter 'hair':

    for (let property in obj) {
      if (obj.hasOwnProperty(property)) {
        console.log(property); // firstName, lastName
        n++;
      }
    }
    console.log(n); // 2
  • 相关阅读:
    洛谷p1056
    __int64
    杭电2057
    4.4清北学堂Day1 主要内容:数论,数学
    递推的一点理解
    高精度减法
    高精度加法
    p1184高手之在一起
    对于rqy今天讲座的一些理解和看法吧
    PHP.21-商品信息管理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9818445.html
Copyright © 2011-2022 走看看