A simple method to determine whether the JavaScript Object is null or the property is null
First, let's talk about the difference between null and undefined:
If typeof is executed on declared but uninitialized and undeclared variables, "undefined" is returned ".
Null indicates a null object Pointer. The typeof operation returns "object ".
Generally, the value of a variable is not explicitly set to undefined, but the opposite is null. For a variable that will save the object, the variable should be explicitly set to save the null value.
1 2 3 4 5 6 7 |
Var bj; Alert (bj); // "undefined" Bj = null; Alert (typeof bj); // "object" Alert (bj = null); // true Bj = {}; Alert (bj = null); // false |
The following two functions are provided by brother Deng. Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 |
/* * Check whether the object is a null object (excluding any readable attributes ). * This method detects both attributes of an object and attributes inherited from the prototype (hasOwnProperty is not used ). */ Function isEmpty (obj) { For (var name in obj) { Return false; } Return true; }; |
Whether the empty object is {} or null. I wrote a test case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Var a = {}; A. name = 'realwall '; Console. log (isEmpty (a); // false Console. log (isEmpty ({}); // true Console. log (isEmpty (null); // true // When the parameter is null, there is no syntax error. That is, although the null pointer object cannot be added, you can use the for in statement. ? /* * Check whether the object is a null object (excluding any readable attributes ). * The method only detects the attributes of the object and does not detect the attributes inherited from the prototype. */ Function isOwnEmpty (obj) { For (var name in obj) { If (obj. hasOwnProperty (name )) { Return false; } } Return true; }; |
Difference between {} and null:
This is very important.
1 2 3 4 5 6 7 |
Var a = {}; Var B = null; A. name = 'realwall '; B. name = 'Jim '; // an error is reported here. B is a null pointer object and cannot be directly added as a normal object. B =; B. name = 'Jim '; // At this time, a and B point to the same object. A. name and B. name are both 'jam' |