判斷Javascript變量是否為空 undefined 或者null(附樣例)


1.變量申明未賦值
var type; //type 變量未賦值
1. type==undefined //true
2. type===undefined //true
3. typeof(type)=='undefined' //true
4. typeof(type)==='undefined' //ture
5. typeof type == 'undefined' //和第3種等價,true
6. typeof type === 'undefined' //和第4種等價,true
7. type==null //true
8. type===null //false
注: typeof type 的值是"undefined",(typeof 返回的是字符串,有六種可能:"number"、"string"、"boolean"、"object"、"function"、"undefined")。
2.變量未申明
1. type1==undefined //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
2. type1===undefined //Error
3. typeof(type1)=='undefined' //true
4. typeof(type1)==='undefined' //ture
5. typeof type1 == 'undefined' //和第3種等價,true
6. typeof type1 === 'undefined' //和第4種等價,true
7. type1==null //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
8. type1===null //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
3.JavaScript undefined 屬性
定義和用法
undefined 屬性用於存放 JavaScript 的 undefined 值。
說明
無法使用 for/in 循環來枚舉 undefined 屬性,也不能用 delete 運算符來刪除它。
undefined 不是常量,可以把它設置為其他值。
當嘗試讀取不存在的對象屬性時也會返回 undefined。
提示和注釋
提示: 只能用 === 運算來測試某個值是否是未定義的,因為 == 運算符認為 undefined 值等價於 null
注釋: null 表示無值,而 undefined 表示一個未聲明的變量,或已聲明但沒有賦值的變量,或一個並不存在的對象屬性


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM