undefined
類型只有一個值,即 undefined
。
null
類型也只有一個值,即 null。
-
null
指空值(empty value)或指曾賦過值,但是目前沒有值 -
undefined
指沒有值(missing value)或指從未賦值
null
是一個特殊關鍵字,不是標識符,我們不能將其當作變量來使用和賦值。
然而 undefined
卻是一個標識符,可以被當作變量來使用和賦值。
null是一種特殊類型,
typeof null === "object"; // true
如果要檢測null,需要使用符合語句進行
var a = null;
(!a && typeof a === "object"); // true
undefined檢測
(function(){
function FeatureXYZ() { /*.. my XYZ feature ..*/ }
// 包含doSomethingCool(..)
function doSomethingCool() {
var helper =
(typeof FeatureXYZ !== "undefined") ?
FeatureXYZ :
function() { /*.. default feature ..*/ };
var val = helper();
// ..
}
doSomethingCool();
})();
NaN
如果數學運算的操作數不是數字類型(或者無法解析爲常規的十進制或十六進制數字),就無法返回一個有效的數字,這種情況下返回值爲 NaN。
isNaN()函數有缺陷,慎重使用或不要使用。
var x = 15 / "foo";
var y = "xyz";
x; // NaN
y; "xyz"
window.isNaN( x ); // true
window.isNaN( y ); // true!