undefined
undefined 的字面意思就是:未定义的值 。这个值的语义是,希望表示一个变量最原始的状态,而非人为操作的结果 。 这种原始状态会在以下 4 种场景中出现:
声明一个变量,但是没有赋
var foo;
console.log(foo); // undefined
访问 foo,返回了 undefined,表示这个变量自从声明了以后,就从来没有使用过,也没有定义过任何有效的值。
访问对象上不存在的属性或者未定义的变量
console.log(Object.foo); // undefined
console.log(typeof demo); // undefined
访问 Object 对象上的 foo 属性,返回 undefined , 表示Object 上不存在或者没有定义名为 foo 的属性;对未声明的变量执行typeof操作符返回了undefined值。
函数定义了形参,但没有传递实参
//函数定义了形参 a
function fn(a) {
console.log(a); // undefined
}
fn(); //未传递实参
函数 fn 定义了形参 a,但 fn 被调用时没有传递参数,因此,fn 运行时的参数 a 就是一个原始的、未被赋值的变量。
使用void对表达式求值
void 0 ; // undefined
void false; // undefined
void []; // undefined
void null; // undefined
void function fn(){} ; // undefined
null
null 的字面意思是:空值 。这个值的语义是,希望表示一个对象被人为的重置为空对象,而非一个变量最原始的状态 。 在内存里的表示就是,栈中的变量没有指向堆中的内存对象。
特殊的typeof null
let data = null;
console.log(typeof data); // "object"
相同点
值相同
console.log( undefined == null )//true
转换Boolean的都是false
console.log( Boolean(undefined) )//false
console.log( Boolean(null) )//false
不同点
数据类型不同
console.log( undefined === null )//false
转换为Number类型的值不同
console.log( Number(undefined) )//NaN
console.log( Number(null) )//0
总结
-
undefined相当于期房。 买了房,但是房子还没建出来。(未定义)
-
null相当于毛坯房。买了房,但是房子没住人,里面是空的。(空值)
-
值是undefined的变量和未声明的变量,typeof运算结果都是“undefined”。运算符typeof运算null的类型时返回“object”。
-
通过禁止使用特殊值undefined,可以有效地确保只在一种情况下typeof才会返回“undefined”:当变量未声明时。这样就可以区别null和undefined。
ps:文末附上汇总文章链接《一名【合格】前端工程师的自检清单【自检ing】》