null
- 表示准备用来保存对象,但是还没有保存的值
- 用法
1、作为函数的参数,表示该函数的参数不是对象
2、作为对象的原型链的终点
console.log(Object.prototype.__proto__) //null
console.log(Number(null)); //0
console.log(null +3);//3
undefined
- 表示变量声明,但是还未初始化的值
- 用法
1、变量声明了但是还没有初始化值时,等于undefined
2、调用函数时,应该提供的参数没有提供,该参数是undefined
3、对象没有赋值的属性,该属性值是undefined
4、函数没有返回值时,默认是undefined
var i;
console.log(i);//undefined
function f(x){
console.log(x);
}
f()//undefined
var obj = {};
console.log(obj.p);//undefined
function fx(){}
console.log(fx())//undefined
- undefined 只有和字符串做运算时不会被转为NaN,和其他类型做运算都会被转为NaN
console.log(undefined + 3);//NaN
console.log(undefined + null); //NaN
console.log(undefined + false);//NaN
//和对象类型做运算时,会默认转为字符串类型操作
console.log(undefined + []);//"undefined"
console.log(undefined + {});//"undefined[object Object]"
console.log(undefined + function(){});//"undefinedfunction (){}"
null、undefined
- 在JavaScript中将一个变量赋值给null和undefined,几乎是没有任何区别的,因为最开始的JavaScript定义“无”的值是null,而null会默认转为0,不能很好的提示错误,后来还增加了undefined。
- null 和 undefined 值相同,但是类型不同
null == undefined //true
null === undegined //false
typeof undefined // "undefined"
typeof null //"object"