在JavaScript中,null
和undefined
是兩個特殊的值,表示缺少值或未定義的狀態。它們之間有以下區別:
null
:表示一個空值或沒有對象的值。它是一個關鍵字,可以被賦值給任何變量。
undefined
:表示一個未定義的值,即變量聲明但未賦值時的默認值。在訪問未初始化的變量或不存在的屬性時,返回undefined
。
區別總結如下:
null
是人為賦予一個”空值”給變量,表示明確地設置為沒有值。
undefined
表示變量未定義或者對象屬性不存在。
在判斷值是否為空時,null
需要使用===
進行嚴格相等比較,而undefined
通常可以使用==
進行松散相等比較。
當函數沒有返回值時,默認返回undefined
。
對于函數參數,如果沒有傳遞對應的參數,其值將是undefined
。
示例代碼:
let nullValue = null;
let undefinedValue;
console.log(nullValue); // 輸出: null
console.log(undefinedValue); // 輸出: undefined
console.log(typeof nullValue); // 輸出: object
console.log(typeof undefinedValue); // 輸出: undefined
console.log(nullValue === undefinedValue); // 輸出: false
console.log(nullValue == undefinedValue); // 輸出: true
function exampleFunc(param) {
console.log(param); // 輸出: undefined
}
exampleFunc(); // 沒有傳遞參數
需要注意的是,盡量避免將undefined
和null
用于除了判斷以外的其他目的。它們在不同上下文中可能會有不同的含義和行為。