我們在進行判斷時,有時會判斷獲取到的對象是否為空值,JS變量值的特殊性,容易犯一些錯。
先上一些不正確的判斷用法
var exp = null;
if (exp == null)
{
alert("is null");
}
exp 為undefined時,也會得到與null相同的結果,雖然null和undefined不一樣。
var exp = null;
if (!exp)
{
alert("is null");
}
如果exp為undefined或者數字零,也會得到與null相同的結果,雖然null和二者不一樣。
var exp = null;
if (typeof(exp) == "null")
{
alert("is null");
}
為了向下兼容,exp為null時,typeof總返回object。
var exp = null;
if (isNull(exp))
{
alert("is null");
}
以下是正確的用法:
var exp = null;
if (!exp && typeof(exp)!="undefined" && exp!=0)
{
alert("is null");
}
盡管如此,我們在DOM應用中,一般只需要用(!exp)來判斷就可以了,因為DOM應用中,可能返回null,可能返回undefined,如果具體判斷null還是undefined會使程序過于復雜。
新聞熱點
疑難解答