javascript ,o檢測屬性,javascript

來源:互聯網
上載者:User

javascript ,o檢測屬性,javascript

   javascript 對象可以看作是屬性的集合,我們經常會檢測集合中成員中所屬關係,判斷屬性是否在這個對象中,那麼我們可以通過in, hasOwnProperty(),propertyIsEnumerable()

等方法。下面分別介紹這些方法:


一、in 檢測屬性是否屬於該對象。

         in 運算子左側是屬性名稱,右側是對象,如果對象的繼承屬性或自有屬性包括這個屬性則返回true:如下

        

        var o={x:1};

        "x " in o   //true x 是 o 的屬性

         “toString"  in  o  // true  o 繼承 toString 屬性


二 hasOwnProperty()方法用來檢測給定的名字是否是對象的自由屬性。對於繼承屬性返回false 例子

      var o={x:1};

      o.hasOwnProperty("x")   //true :o 有一個自由屬性x

      o.hasOwnproperty("toString);  //false toString 是繼承屬性:


三、propertyIsEnumerable()是hasOwnProperty()增強版,不僅要檢驗是對象的自由屬性,還要檢驗該屬性,是否可枚舉。如下

     var o={x:1};

      o.propertyIsEnumerable(x)  // true ,x 是o的自由屬性,且可以枚舉

     Object.property.propertyIsEnumerable("toStirng") //false 不可枚舉

以上除了使用in運算子外,更簡單的方法使用“!==” 判斷屬性是否 undefined 的屬性,如下代碼:

  var o={x:1};

  o.x!==undefined   //true o 中有屬性x

  o.toString!==undefined //true o 中有繼承屬性 toString

但是有一種情況只能使用in 運算子 而不能使用上面的方式

  如下:

    var o={x:undefined};

    o.x!==undefined  //false 屬性存在 但值為undefined 

     "x"  in o  // true 存在屬性x


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.