- null的類型是個(gè)一對(duì)象夜焦,代表一個(gè)空值壳澳。
- undefined的類型是一個(gè)對(duì)象,代表沒(méi)有定義茫经。
- NaN的類型是一個(gè)number巷波,代表不是數(shù)值類型。
1. null
把一個(gè)變量的值設(shè)置為null卸伞,就表示該變量的值不是有效的對(duì)象,數(shù)組抹镊,數(shù)字,字符串和布爾值荤傲。null對(duì)應(yīng)類型Object垮耳,布爾值false,數(shù)字0遂黍,字符串“null”
var test = null;
//類型氨菇,輸出object
document.write( typeof (test));
document.write("<br/>");
//字符串儡炼,輸出nulltest
document.write(test + 'test');
document.write("<br/>");
//數(shù)字,輸出10
document.write(test + 10);
document.write("<br/>");
//布爾值查蓉,輸出false
if (test) {
document.write("true");
}
if (!test) {
document.write("false");
}
2. undefined
當(dāng)你使用一個(gè)未被聲明的變量時(shí)或者已經(jīng)聲明了但還沒(méi)有賦值乌询,又或者使用了一個(gè)不存在的對(duì)象屬性,返回的就是undefined豌研。undefined對(duì)應(yīng)類型undefined妹田,布爾型false,字符串undefined鹃共,數(shù)字計(jì)算結(jié)果一定是NaN
var test;
//類型鬼佣,輸出undefined
document.write( typeof (test));
document.write("<br/>");
//字符串,輸出undefinedtest
document.write(test + 'test');
document.write("<br/>");
//數(shù)字霜浴,輸出NaN
document.write(test + 10);
document.write("<br/>");
//布爾值晶衷,輸出false
if (test) {
document.write("true");
}
if (!test) {
document.write("false");
}
3. NaN
NaN 屬性代表一個(gè)“不是數(shù)字”的值。這個(gè)特殊的值是因?yàn)檫\(yùn)算不能執(zhí)行而導(dǎo)致的阴孟,不能執(zhí)行的原因要么是因?yàn)槠渲械倪\(yùn)算對(duì)象之一非數(shù)字(例如晌纫, "abc" / 4),要么是因?yàn)檫\(yùn)算的結(jié)果非數(shù)字(例如永丝,除數(shù)為零)锹漱。判斷一個(gè)變量是否為NaN。ES6提供了一個(gè)新的 Number.isNaN() 函數(shù)慕嚷,這是一個(gè)不同的函數(shù)哥牍,并且比老的全局 isNaN() 函數(shù)更可靠。
// 兩大驚人特性
// 1 這的是Number型的
console.log(typeof NaN === "number"); // logs "true"
// 2 自己和自己并不相等
console.log(NaN === NaN); // logs "false"
4. null和undefined的比較
null == undefined 返回true
null===undefined 返回false