javascript面试题之null和undefined的区别

来源:互联网 发布:苹果免费下载软件 编辑:程序博客网 时间:2024/05/17 09:07

javascript中有两个值表示“空”,null和undefined。
在一些情况下,null和undefined几乎是一样的。例如:

if (!undefined) {// undefined is false    console.log('undefined is false');}if (!null) {// null is false    console.log('null is false');}//注意ifundefined == null) {// true    console.log('undefined == null');}

但是null和undefined仍然存在一些区别:
1.类型不一样

console.log(typeof undefined); //undefinedconsole.log(typeof null); //object

null居然是一个object!所以,我们可以这么理解,null是一个对象的占位符,表示这个对象还未初始化,是个”空对象”;而undefined表示压根没人对这个变量做定义,没人知道这到底是个什么玩意儿。

2.转为数值时,值不一样

console.log(Number(undefined)); //NaNconsole.log(undefined + 10);//NaNconsole.log(Number(null)); //0console.log(null + 10); //10

undefined转为数值NaN,null转为数值0。

3.===运算符可区分null和undefined

if(null === undefined) {//false    console.log("null === undefined")//never}

4.null的典型用法
(1) 作为函数的参数,表示该函数的参数不是对象。

function testObj(obj) {    if(null == obj) {        // 异常处理,比如创造一个新对象    }    //……}

(2) 作为对象原型链的终点。

Object.getPrototypeOf(Object.prototype)// null

5.undefined的典型用法
(1)变量被声明了,但没有赋值时,就等于undefined。

var i;i // undefined

(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。

function f(x) {    console.log(x)}f() // undefined

(3)对象没有赋值的属性,该属性的值为undefined。

var  o = new Object();o.p // undefined

(4)函数没有返回值时,默认返回undefined。

var x = f();x // undefined
0 0
原创粉丝点击