The Null type is the second data type with only one value. This special value is null. From a logical point of view, the null value represents a null object pointer, and this is exactly what happens when using the typeof operator to detect a null value. The reason for returning "object".
As shown in the following example:
var car =null; alert(typeof null); //object(其实这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来)
If the defined variables are intended to be used by the user to save objects in the future, then it is best to The variable is initialized to null and no other value. In this way, you can know whether the corresponding variable has saved a reference to an object by directly checking the null value.
As shown in the following example:
if(car != null){ //对car执行某些操作 }
In fact , the undefined value is derived from the null value, so ECMA-262 stipulates that their equality test should return true:
alert(null == undefined) //true
Here, the equality operator (==) between null and undefined always returns true, but note that this operator converts its operands for comparison purposes.
Although null and undefined have such a relationship, their uses are completely different. As mentioned above, there is no need to explicitly set the value of a variable to undefined under any circumstances. The same can be seen The rules don't apply to null. In other words, as long as a variable that is intended to hold an object does not actually hold an object, you should explicitly let the variable hold a null value. Doing so not only reflects the convention of null as a null object pointer, but also helps to further distinguish null and undefined.
Undefined and Null
Undefined This value indicates that the variable does not contain a value.
You can clear a variable by setting its value to null.
How to determine whether a variable is null in a program.
var exp = null; if (!exp && typeof exp != "undefined" && exp != 0) { alert("is null"); }
typeof exp != "undefined" excludes undefined;
exp != 0 excludes the numbers zero and false.
Simpler and correct way:
var exp = null; if (exp === null) { alert("is null"); }
The above is the detailed content of What type is js null. For more information, please follow other related articles on the PHP Chinese website!