null是js中的关键字,表示空值;null可以看作是object的一个特殊的值,如果object值为空,表示这个对象不是有效对象;
undefined不是js中的关键字,是一个全局变量,是Global的一个属性;
以下情况会返回undefined:
- 变量已声明,但未赋值,就等于undefined;
- 函数调用时,没有提供实参,该参数等于undefined;
function fun1( a ){
console.log( a )
}
fun1(); //undefined (形参只是声明了,未传入实参=未赋值)
- 使用一个对象属性时,但该属性未赋值或不存在,该属性值为undefined;
- 函数没有返回值时,默认返回undefined;
var a = function(){};
console.log(a); //undefined
一、相似性
在JavaScript中,null与undefined表示“无”,都是原始类型的值,保存在栈中;
譬如:
将变量a 赋值为null与undefined,两种写法几乎没有区别;
var a = null;
var a = undefined;
unll与undefined在if语句中,都会被自动转为false;
if(!undefined)
console.log(" undefined is false ")
//undefined is false
if(!null)
console.log(" null is false ")
//null is false
console.log(undefined == null); // true (作比较时,unll与undefined自动转换为false)
//PS : 三等与两等不同;
console.log(undefined === null); // false (unll为0与undefined为false,三等为false)
二、区别
1.类型不一样;
2.转化值时不一样;
类型:
console.log( typeOf undefined ); // undefined
console.log( typeOf null ); // object
转化值:
console.log( Number(undefined) ); // NaN
console.log( Number(undefined+10) ); // NaN
console.log( Number(null) ); // 0
console.log( Number(null+10) ); // 10
三、使用
null当使用完一个较大的对象时,需要对其进行释放内存,可将该对象设置为null。
var arr = [ 111,222,333];
arr = null; //释放指向数组的引用;