javascript中如果判断值为null

 一般新手都会犯这样的错误,我当初也是啦




var str = null;
if (str == null)
{
alert("str is null");
}


 str 为未定义 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。


要同时判断 null 和 undefined 时可使用下面的方法




var str = null;
if (!str)
{
alert("str is null");
}


如果 str 为 undefined,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。




var str = null;
if (typeof str == "null")
{
alert(" str is null");
}


SyntaxHighlighter.highlight();