相同
二者幾乎是等價(jià)的
undefined屡立、null在 if語(yǔ)句中都可以當(dāng)成false使用
if (!undefined) {
console.log('undefined is false');
}
// undefined is false
if (!null) {
console.log('null is false');
}
// null is false
不同
不過還是有小小的不同
1、數(shù)據(jù)類型
typeof null //返回“object”
typeof undefined //返回"undefined"
2憔杨、進(jìn)行數(shù)值運(yùn)算時(shí)
5+"null" //返回5,null轉(zhuǎn)換為0
5+"undefined" //返回NaN,undefined轉(zhuǎn)換為NaN
3、用法及含義(null表示“空值”胖腾,undefined表示“未定義”)
#null
調(diào)用函數(shù)時(shí)霍比,某個(gè)參數(shù)未設(shè)置任何值幕袱,這時(shí)就可以傳入null
function f1(x,y){return x}
f1(4,null); //5
f1(4); //5
#undefined
#以下情況會(huì)返回undefined
--- 聲明變量,但沒有賦值悠瞬,會(huì)返回undefined
var x;
x; // undefined
--- 對(duì)象沒有賦值的屬性
var x ={};
x.p; // undefined
--- 函數(shù)無(wú)返回值
function f(){};
f()// 默認(rèn)返回undefined
--- 調(diào)用函數(shù)時(shí)们豌,應(yīng)該提供的參數(shù)沒有提供,該參數(shù)等于 undefined
function f(x){return x};
f()// undefined
--- typeof 未聲明浅妆、未賦值的變量(可以使用這個(gè)方法判斷某個(gè)變量是否存在)
typeof v // undefined
if(typeof v === "undefined"){
// ...正確寫法
}
if(v){
// ...錯(cuò)誤寫法望迎,ReferenceError: v is not defined
}
本文為閱讀阮一峰大神《JavaScript標(biāo)準(zhǔn)參考教程》之后寫的總結(jié),如果大家覺得有不清楚的凌外,可以去看大神寫的教程??