萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 正確判斷 undefined 的姿勢:typeof 運算符深度解析

為什麼 x === undefined 不可靠?

// 全局作用域下 undefined 可被覆蓋(非嚴格模式)
undefined = 'I am redefined'; // 老舊瀏覽器允許
var x;
console.log(x === undefined); // false!因為 undefined 已被篡改

// 區塊作用域 const/let 不受影響,但習慣危險

ES5 嚴格模式下 undefined 為只讀,但為了代碼健壯性、跨環境兼容,**永遠使用 typeof** 。

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 的特殊行為:未聲明變量不拋錯

// 這是 typeof 唯一不拋 ReferenceError 的情況
typeof notDeclaredVariable; // "undefined" - 安全

// 其他操作都會拋錯
// notDeclaredVariable; // ReferenceError
// notDeclaredVariable === undefined; // ReferenceError
// 'prop' in notDeclaredVariable; // ReferenceError

這使得 typeof 成為檢測全局變量/特性是否存在的唯一安全方式。

現代替代方案

1. 默認參數 (ES6) —— 推薦用於函數參數

function foo(arg = 'default') {
  // arg 為 undefined 時自動使用默認值
  // null 會保持 null,不會觸發默認值
}

2. 空值合並運算符 ?? (ES2020) —— 推薦用於賦值

var val = possiblyUndefined ?? 'default';
// 僅當左側為 null/undefined 時使用右側
// ''、0、false 會保留原值(區別於 ||)

3. 可選鏈 ?. (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' 這一歷史遺留行為,同樣是避坑關鍵。

copyright © 萬盛學電腦網 all rights reserved