undefined:表示“未定义”或不存在,即由于目前没有定义,所以此处暂时没有任何值。
null:表示空值,即此处的值为空。
相同点
1、都是js的基本数据类型,一般将它们看成两个特殊值
2、将一个变量赋值为undefined或null,语法效果几乎没区别
3、在if语句中,都会被自动转为false
4、严格相等运算符(===):undefined和null与自身严格相等
相等运算符(==):undefined和null只有与自身比较,或者互相比较时,才会返回true;
与其他类型的值比较时,结果都为false
// 严格相等运算符 ===
null === null // true
undefined === undefined // true
null === undefined // false
// 相等运算符 ==
null == null // true
undefined == undefined // true
null == undefined // true
false == null // false
false == undefined // false
0 == null // false
0 == undefined // false
5、 null和undefined都无法转成对象
// 如果参数为空(或者为undefined和null),Object()返回一个空对象。
var obj = Object();
// 等同于
var obj = Object(undefined);
var obj = Object(null);
obj instanceof Object // true
区别
1、转为数值
- null是一个表示“空”的对象,转为数值时为0
- undefined是一个表示"此处无定义"的原始值,转为数值时为NaN
Number(null) // 0
5 + null // 5
Number(undefined) // NaN
5 + undefined // NaN
2、转为字符串
- undefined:转为字符串'undefined'
- null:转为字符串'null'
String(null) // 'null'
'5' + null // '5null'
String(undefined) // 'undefined'
'5' + undefined // '5undefined'
3、typeof
typeof null // 'object'
typeof undefined // 'undefined'
4、Object.prototype.toString.call()
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
5、JSON
- JSON 对象的值可以是null,不能使用undefined
JSON.parse('{"a":null}') // {a: null}
// 报错
JSON.parse('{"a":undefined}') // SyntaxError: Unexpected token u in JSON at position 5
- 如果对象的属性是undefined,该属性会被JSON.stringify()过滤
JSON.stringify({a: null}) // '{"a":null}'
JSON.stringify({a: undefined}) // '{}'
- 如果数组的成员是undefined,该成员会被JSON.stringify()转成null
JSON.stringify([null]) // '[null]'
JSON.stringify([undefined]) // '[null]'
用法
null:
- 调用函数时,某个参数未设置任何值,这时就可以传入null,表示该参数为空
// 函数参数不是必需的,没有办法只省略靠前的参数,而保留靠后的参数。
// 如果一定要省略靠前的参数,只有显式传入undefined
// 或者传入null,表示该参数为空
function f (a, b) {
console.log(a, b);
}
f(, 2) // 报错 SyntaxError: Unexpected token ','
f(undefined, 2) // undefined 2
f(null, 2) // null 2
// 生成一个不继承任何属性(比如没有toString()和valueOf()方法)的对象
var obj = Object.create(null);
obj.valueOf() // TypeError: obj.valueOf is not a function
typeof obj // 'object'
obj instanceof Object // false
// xhr.send()的参数为null,表示发送请求的时候,不带有数据体
var xhr = new XMLHttpRequest();
// ...
xhr.open('GET', '/endpoint', true);
xhr.send(null);
- 原型链的尽头是null。null没有任何属性和方法,也没有自己的原型
Object.getPrototypeOf(Object.prototype) // null
undefined:
- 返回undefined的典型场景
// 变量声明了,但没有赋值
var i;
i // undefined
// 调用函数时,应该提供的参数没有提供,该参数等于 undefined
function f(x) {
return x;
}
f() // undefined
// 对象没有赋值的属性
var o = new Object();
o.p // undefined
// 函数没有返回值时,默认返回 undefined
function f() {}
f() // undefined
- 返回undefined的其他场景
// void运算符不返回任何值,或者说返回undefined
void 0 // undefined
// 严格模式的函数体内部this是undefined,而不是window
function f() {
'use strict';
console.log(this === undefined);
}
f() // true
The End
参考连接: