if (value === undefined) { ... } // 若 value 未聲明會拋 ReferenceError
if (value == undefined) { ... } // 同理,且會匹配 null
if (typeof value === 'undefined') {
console.log('未定義或未聲明');
}
優勢:即使變量未聲明也不會報錯,返回 'undefined' 字符串。
| 表達式 | 返回值 |
|---|---|
typeof undefined | "undefined" |
typeof 'abc' | "string" |
typeof 123 | "number" |
typeof true | "boolean" |
typeof {} | "object" |
typeof [] | "object" |
typeof null | "object" (著名bug) |
typeof function(){} | "function" |
typeof Symbol() | "symbol" (ES6) |
typeof 10n | "bigint" (ES10) |
typeof null === 'object' → 需額外 value === null 判斷。typeof [] === 'object' → 用 Array.isArray(arr)。'function',現代瀏覽器返回 'object' → 用 obj instanceof RegExp。function isUndefined(val) {
return typeof val === 'undefined';
}
function isNull(val) {
return val === null;
}
function isNullOrUndefined(val) {
return val == null; // 利用 == 僅匹配 null/undefined
}
function getType(val) {
if (val === null) return 'null';
if (Array.isArray(val)) return 'array';
if (val instanceof RegExp) return 'regexp';
if (val instanceof Date) return 'date';
return typeof val;
}
var undef = void 0; // 永遠是真正的 undefined,不可被篡改(舊版瀏覽器 window.undefined 可被賦值)
console.log(void 0 === undefined); // true