Determine if the JavaScript object is null or the property is empty

Source: Internet
Author: User
Tags null null hasownproperty

Transferred from: http://blog.csdn.net/yiluoak_47/article/details/7766760

First, the difference between null and undefined:
Executes typeof on declared but uninitialized and undeclared variables, returning "undefined".
Null represents an empty object pointer, and the typeof operation returns "Object".


Generally do not explicitly set the value of the variable to undefined, but null instead, for the variable that will save the object, you should explicitly let the variable hold a null value.

var Bj;alert (BJ); // "undefined" NULL ; alert (typeof BJ); // "Object" null); // trueBJ =null); // false

The following two functions are:

/* * * Detects if the object is an empty object (does not contain any readable properties). The * method detects both the properties of the object itself and the attributes inherited from the prototype (and therefore does not make hasOwnProperty)*/function    isEmpty (obj) {  for (var in obj) {        returnfalse;    }     returntrue;};

Whether the empty object here is {}, or null. I wrote a test case.

var a ='realwall'; Console.log (IsEmpty (a)); // falseConsole.log (IsEmpty ({})); // trueconsole.log (IsEmpty (null)); // true

Note There is no syntax error when the parameter is null Oh, that is, although you cannot add a property to a NULL Null pointer object, you can use the for in statement.

/**/function isownempty (obj    ) {for (var in  obj) {         if (Obj.hasownproperty (name)) {            returnfalse;        }    }     return true ;}

The difference between {} and null:

 var  a = {};  var  b = null  ;a.name  =  "  Realwall   " ;b.name  =  '   b = A;b.name  = "  jim   "  //  at this point A and B point to the same object. A.name, b.name are ' jam '  

Determine if the JavaScript object is null or the property is empty

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.