◆
JavaScript null、undefined 与 undeclared 区别详解
null
指曾赋过值,但是目前没有值,表示一个“空”的对象,转为数值时为 0
场景
- 作为函数的参数,表示该函数的参数不是对象。
- 当使用完一个比较大的对象时,需要对其进行释放内存时,设置为
null - 主动释放一个变量引用的对象,表示一个变量不再指向任何对象地址
为什么 type of null 是 object
原理是这样的,不同的对象在底层都表示为二进制,在 JavaScript 中二进制前三位都为 0 的话会被判 断为 object 类型,null 的二进制表示是全 0,自然前三位也是 0, 所以执行 typeof 时会返回 object。
undefined
是一个表示"此处无定义"的原始值,转为数值时为 NaN,表示已在作用域中声明但还没有赋值的变量。
场景
- 变量声明了,但没有赋值
- 调用函数时,应该提供的参数没有提供,该参数等于
undefined - 对象没有赋值的属性
- 函数没有返回值时,默认返回
undefined
var i;
i; // undefined
function f(x) {
return x;
}
f(); // undefined
var o = new Object();
o.p; // undefined
function f() {}
f(); // undefined
一些示例
typeof null; // "object"
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
isNaN(1 + null); // false
isNaN(1 + undefined); // true
undeclared
还没有在作用域中声明过的变量
var a;
console.log(typeof a); // undefined
console.log(typeof b); // undefined
console.log(b); // Uncaught ReferenceError: b is not defined
由上述代码可见,typeof 对
undefined与undeclared的变量识别后都是undefined,但实际上undeclared的变量在 使用时会报Uncaught ReferenceError: b is not defined错误

还没有留言,来发表第一条吧~