x === undefined 不可靠?// 全局作用域下 undefined 可被覆蓋(非嚴格模式)
undefined = 'I am redefined'; // 老舊瀏覽器允許
var x;
console.log(x === undefined); // false!因為 undefined 已被篡改
// 區塊作用域 const/let 不受影響,但習慣危險
ES5 嚴格模式下 undefined 為只讀,但為了代碼健壯性、跨環境兼容,**永遠使用 typeof** 。
| 運算元類型 | 返回值 | 示例 |
|---|---|---|
| Undefined | "undefined" | typeof undeclaredVar, typeof undefined |
| Null | "object" | typeof null (著名歷史遺留 Bug) |
| Boolean | "boolean" | typeof true |
| Number | "number" | typeof 42, typeof NaN, typeof Infinity |
| String | "string" | typeof 'hello' |
| Symbol (ES6) | "symbol" | typeof Symbol() |
| BigInt (ES2020) | "bigint" | typeof 9007199254740991n |
| Function | "function" | typeof function(){} , typeof alert |
| Object (含 Array, Date, RegExp...) | "object" | typeof {}, typeof [] |
// 1. 判斷變量是否未聲明 或 聲明未賦值
if (typeof myVar === 'undefined') {
console.log('myVar 未聲明或為 undefined');
}
// 2. 判斷對象屬性是否存在(不觸發 ReferenceError)
if (typeof obj.prop === 'undefined') {
console.log('obj.prop 不存在或為 undefined');
}
// 3. 判斷函數參數是否傳遞
function foo(arg) {
if (typeof arg === 'undefined') {
arg = 'default';
}
}
// 4. 區分 null 和 undefined
function check(val) {
if (val === null) return 'null';
if (typeof val === 'undefined') return 'undefined';
return 'other';
}
var utils = {
isUndefined: function (val) {
return typeof val === 'undefined';
},
isDefined: function (val) {
return typeof val !== 'undefined';
},
// 區分「未聲明」與「聲明為 undefined」(極少用)
isDeclared: function (varName, scope) {
scope = scope || window;
return varName in scope; // 'prop' in obj 不讀取值,只檢查鍵存在
}
};
// 測試
var declaredButUndefined;
console.log(utils.isUndefined(declaredButUndefined)); // true
console.log(utils.isUndefined(notDeclaredAtAll)); // true (不拋錯)
console.log(utils.isDeclared('declaredButUndefined')); // true
console.log(utils.isDeclared('notDeclaredAtAll')); // false
// 這是 typeof 唯一不拋 ReferenceError 的情況
typeof notDeclaredVariable; // "undefined" - 安全
// 其他操作都會拋錯
// notDeclaredVariable; // ReferenceError
// notDeclaredVariable === undefined; // ReferenceError
// 'prop' in notDeclaredVariable; // ReferenceError
這使得 typeof 成為檢測全局變量/特性是否存在的唯一安全方式。
function foo(arg = 'default') {
// arg 為 undefined 時自動使用默認值
// null 會保持 null,不會觸發默認值
}
?? (ES2020) —— 推薦用於賦值var val = possiblyUndefined ?? 'default';
// 僅當左側為 null/undefined 時使用右側
// ''、0、false 會保留原值(區別於 ||)
?. (ES2020) —— 推薦用於對象屬性鏈var city = user?.address?.city ?? '未知';
// 任意環節為 null/undefined 直接返回 undefined,不拋錯
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
if (x == undefined) | == 會匹配 null,且 undefined 可被篡改 | typeof x === 'undefined' |
if (!x) | 無法區分 undefined、null、0、''、false | 明確語義用嚴格判斷 |
typeof x == 'undefined' (無引號) | 語法錯誤,undefined 是標識符 | typeof x === 'undefined' |
typeof null === 'null' | typeof null 返回 "object" | val === null 判斷 null |
typeof x === 'undefined' 是判斷 undefined 的**唯一安全、標準、跨環境**方式。現代代碼中,函數參數用默認參數,賦值兜底用 ??,屬性訪問用 ?.,僅在需檢測「變量是否聲明」或「動態屬性是否存在」時使用 typeof。理解 typeof null === 'object' 這一歷史遺留行為,同樣是避坑關鍵。