一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

javascript null对象详解

时间:2011-09-07 编辑:简简单单 来源:一聚教程网

网页特效 null对象详解

null

    这是一个对象,但是为空。因为是对象,所以 typeof null  返回 'object' 。

    null 是 JavaScript 保留关键字。

    null 参与数值运算时其值会自动转换为 0 ,因此,下列表达式计算后会得到正确的数值:

    表达式:123 + null    结果值:123

    表达式:123 * null    结果值:0

以下是不正确的方法:
var exp = null;
if (exp == null)
{
    alert("is null");
}

exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法。
var exp = null;
if (!exp)
{
    alert("is null");
}

如果 exp 为 undefined,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined、数字零、false 时可使用本法。
var exp = null;
if (typeof exp == "null")
{
    alert("is null");
}

为了向下兼容,exp 为 null 时,typeof null 总返回 object,所以不能这样判断。
var exp = null;
if (isNull(exp))
{
    alert("is null");
}

VBScript 中有 IsNull 这个函数,但 JavaScript 中没有。

以下是正确的方法:
var exp = null;
if (!exp && typeof exp != "undefined" && exp != 0)
{
    alert("is null");
}

    typeof exp != "undefined" 排除了 undefined;
    exp != 0 排除了数字零和 false。

更简单的正确的方法:
var exp = null;
if (exp === null)
{
    alert("is null");
}

热门栏目