定义
null:关键字,表示”空值”,typeof null返回"object"undefined:预定义全局变量,typeof undefined返回"undefined"
转义
!!null; // false
!!undefined; // false
Number(null); // 0
Number(undefined); // NaN
null == undefined; // true
null === undefined; // false
判定
var isNull = function (obj) { return obj === null; };
var isUndefined = function (obj) { return obj === void 0; };
undefined 的典型场景
- 变量声明未赋值
- 函数参数未提供
- 对象属性未赋值
- 函数无返回值
- 解构赋值时触发默认值(
null不会触发默认值)
const { a = "a", b = "b" } = { a: null };
// a → null, b → "b"