First let’s talk about the difference between null and undefined:
Executing typeof on declared but uninitialized and undeclared variables will return "undefined".
null represents a null object pointer, and the typeof operation will return "object".
Generally, the value of a variable is not explicitly set to undefined, but on the contrary, for a variable that will save an object, the variable should be explicitly allowed to save the null value.
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 Senior Brother Deng, thank you.
/* * 检测对象是否是空对象(不包含任何可读属性)。 * 方法既检测对象本身的属性,也检测从原型继承的属性(因此没有使hasOwnProperty)。 */ function isEmpty(obj) { for (var name in obj) { return false; } return true; };
The empty object mentioned here 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 //注意参数为null时无语法错误哦,即虽然不能对null空指针对象添加属性,但可以使用for in 语句 ? /* * 检测对象是否是空对象(不包含任何可读属性)。 * 方法只既检测对象本身的属性,不检测从原型继承的属性。 */ function isOwnEmpty(obj) { for(var name in obj) { if(obj.hasOwnProperty(name)) { return false; } } return true; };
{} and null:
This thing is very important.
var a = {}; var b = null; a.name = 'realwall'; b.name = 'jim'; //这里会报错,b为空指针对象,不能像普通对象一样直接添加属性。 b = a; b.name = 'jim'; //此时 a 和 b 指向同一个对象。a.name, b.name 均为'jam'