javascript,檢測對象中是否存在某個屬性

來源:互聯網
上載者:User

標籤:javascrip   color   log   結果   通過   string   判斷   ring   efi   

檢測對象中屬性的存在與否可以通過幾種方法來判斷。1.使用in關鍵字。該方法可以判斷對象的自有屬性和繼承來的屬性是否存在。var o={x:1};"x" in o;            //true,自有屬性存在"y" in o;            //false"toString" in o;     //true,是一個繼承屬性 2.使用對象的hasOwnProperty()方法。該方法只能判斷自有屬性是否存在,對於繼承屬性會返回false。var o={x:1};o.hasOwnProperty("x");       //true,自有屬性中有xo.hasOwnProperty("y");       //false,自有屬性中不存在yo.hasOwnProperty("toString"); //false,這是一個繼承屬性,但不是自有屬性 3.用undefined判斷自有屬性和繼承屬性均可判斷。var o={x:1};o.x!==undefined;        //trueo.y!==undefined;        //falseo.toString!==undefined  //true該方法存在一個問題,如果屬性的值就是undefined的話,該方法不能返回想要的結果,如下。var o={x:undefined};o.x!==undefined;        //false,屬性存在,但值是undefinedo.y!==undefined;        //falseo.toString!==undefined  //true 4.在條件陳述式中直接判斷var o={};if(o.x) o.x+=1;  //如果x是undefine,null,false," ",0或NaN,它將保持不變

 

javascript,檢測對象中是否存在某個屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.