javascript学习指南_JavaScript中null与undefined区别

更新时间:2019-09-04    来源:网页配色    手机版     字体:

【www.bbyears.com--网页配色】

null 与 undefined 是 JavaScript 的两个类型,类型的值如下:

类型 值 null 只有一个值 null undefined 只有一个值 undefined

null 表示变量取值为 null – 换句话说,取值即不是字符串也不是数字也不是真假值也不是对象。
undefined 表示变量已经声明,但未赋值,或赋值 undefined。

比如:

var a; // 变量已声明,未赋值
var b = undefined; // 变量已声明,则赋值 undefined
a === b;
a === b 的输出结果是 true。

所以我们可以简单地区别它们:
undefined 表示没找到变量的值 – 找不到值
null 表示找到变量的值是 null – 找得到值

再看判断 null 与 undefined

这里所说的判断,是指判断变量的值是否就是 null 或 undefined


null 与 undefined 是它们所属类型的唯一一个值。所以判断方法非常方便,只要我们使用恒等比较(===)。
a 即 undefined

var a;
a === undefined;

上面的代码将输出 true,即 a 为 undefined。

a 为 null
var a = null;
a === null;
上面的代码将输出 true,即 a 是 null。

当然,恒等比较有一个前提,就是变量已经存在,如果变量尚未声明,引用未声明的变量会抛出错误。
i === undefined;

以上代码执行后会抛出错误:

ReferenceError: i is not defined

所以使用 typeof 来检查变量是否为 undefined 会更安全:
typeof i === "undefined"; // 如果 i 未声明,或 i 已声明但未赋值,结果为 true
但 typeof 检查变量值是否为 null 时,输出结果是 “object”,这个结论并不准确。以下方法才是对的且安全的:

var a = null;
Object.prototype.toString.call(a).slice(8, -1);

它会输出 Null,表示变量 a 的值是 null。

本文来源:http://www.bbyears.com/wangyezhizuo/66247.html