JS中的not defined和undefined

JS中關(guān)于變量常遇到的錯(cuò)誤有兩個(gè),一個(gè)是“xx is not defined”,另一個(gè)是“undefined”。

一.區(qū)別

1."not defined"

var a;  //只聲明變量,未賦值
console.log(a);  //undefined

2."undefined"

//var a;
console.log(a);  //未聲明變量且未賦值,a is not defined

__結(jié)論:
聲明變量卻沒(méi)有對(duì)其進(jìn)行賦值,即變量undefined;
未聲明也未賦值變量,即變量not defined.
undefined:不明確的,也就是不知道用來(lái)干嘛的;
not defined: 未定義的. __


注:若變量a沒(méi)有通過(guò)var聲明,但是卻賦值了,如:

a = 1;
console.log(a);  //1
console.log(window.a)  //1

當(dāng)變量不加var聲明時(shí),默認(rèn)在變量前面自動(dòng)添加window.,也就成了window的屬性。

再看一個(gè)例子:

(function aa(){
    var a = 1;
        b = 2;
})();
console.log(a);  //a is not defined
console.log(window.a);  //undefined
console.log(b);  //2
console.log(window.b);  //2

結(jié)論:
如果在方法中聲明變量,則為局部變量.
如果是在全局域中聲明,則為全局變量.


二.判斷

兩者都可以用typeof進(jìn)行判斷:

var a;  
if (typeof(a) == "undefined") {
    alert("undefined");
} 
if (typeof(b) == "undefined") {
    alert("undefined");
}

三.null

既然提到not defined和undefined,有一個(gè)不得不提的就是null了。

 console.log(typeof(null));  //Object

null是js的關(guān)鍵字,其含義為“非對(duì)象”。不過(guò)通常認(rèn)為它是null這個(gè)類(lèi)型下的唯一一個(gè)成員,它可以表示數(shù)字、字符和對(duì)象是“無(wú)值”的

undefined也是表示無(wú)值

    console.log(null == undefined);  //true
    console.log(null === undefined);  //false
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容