undefined既是一個基本數據類型也是一個原始值數據
- 系統會給一個未賦值的變量賦值為undefined,返回的類型也是undefined
var a;
console.log(a); // 值undefined
console.log(typeof a); // 類型undefined
- 調用一個有參數的函數但是不傳參,這個參數也是undefined
function test(a){
console.log(a); // 值undefined
console.log(typeof a); // 類型undefined
return a // // 值undefined
}
console.log(test());
- 函數內部沒有顯式return東西時,系統默認返回undefined
function test(){
var a = 9
}
console.log(test()); // undefined
undefined還是全局window上的一個屬性
window.undefined.png
- 這個屬性是只讀的,不可配置,不可枚舉
console.log(window.undefined); // undefined
window.undefined = '123'
console.log(window.undefined);
for (let k in window) {
if(k === undefined){
console.log("訪問到了");
}
}
undefined.png
- 不可重新定義
Object.defineProperty(window, "undefined", {
enumerable: true,
writable: true,
configurable: true
})
//直接報錯
Uncaught TypeError: Cannot redefine property: undefined
at Function.defineProperty (<anonymous>)
at test.html:9
undefined可以做變量名嗎??
- 全局作用域下
var undefined = 1
console.log(undefined); // undefined
console.log(window.undefined); // undefined
- 局部作用域下
function test(){
var undefined = 1
console.log(undefined); // 1
}
test()
undefined在局部作用域可以作為變量,undefined不是關鍵字也不是保留字,上面也說了在全局下,undefined是只讀的,所以在局部作用域中就可以使用,嚴格模式下仍然可以。但是開發中還是避免使用它做變量名
判斷類型
如果要判斷某個變量是否是undefined,必須使用“===”而不能使用“==”
var a;
if(a === undefined){
console.log("執行了"); // 可以執行
}
var b;
if(a == undefined){
console.log("執行了"); // 可以執行
}
為的就是與null進行區分,當a = null時,a == undefined返回的結果就是true
var a = null;
if(a == undefined){
console.log("執行了");
}