Simple way to determine whether a JavaScript object is null or a property is null

  • 2020-03-30 04:01:01
  • OfStack

First, the difference between null and undefined:

Typeof is executed on declared but uninitialized and undeclared variables, both returning "undefined".

Null represents an empty object pointer, and the typeof operation returns "object".

The value of a variable is not explicitly set to undefined, but null is, on the contrary, explicitly set to null for the variable to be stored.


var bj;
alert(bj); //"undefined"
bj = null;
alert(typeof bj); //"object"
alert(bj == null); //true
bj = {};
alert(bj == null); //false

The following two functions were given to me by brother deng. Thank you.



function isEmpty(obj)
{
for (var name in obj)
{
return false;
}
return true;
};

The empty object is {} or null. I wrote a test case.


var a = {};
a.name = 'realwall';
console.log(isEmpty(a)); //false
console.log(isEmpty({})); //true
console.log(isEmpty(null)); //true

//Note that there is no syntax error when the parameter is null, that is, you can use the for in statement, although you cannot add properties to null null pointer objects

  
?

function isOwnEmpty(obj)
{
for(var name in obj)
{
if(obj.hasOwnProperty(name))
{
return false;
}
}
return true;
};

Difference between {} and null:

This is very important.


var a = {};
var b = null;

a.name = 'realwall';
b.name = 'jim'; //There will be an error here, b is a null pointer object, you can't add properties directly like normal objects.
b = a;
b.name = 'jim'; // At this time  a  and  b  Point to the same object. a.name, b.name  Are all 'jam'


Related articles: