JavaScript類型判斷的多種方法
更新時間:2026年01月15日 09:00:22 作者:BillKu
本文介紹了JavaScript中多種類型判斷方法,包括基礎類型判斷、數(shù)組判斷、null判斷、復雜類型判斷、構(gòu)造函數(shù)實例判斷、NaN判斷、類型安全比較等,并提供了一些實用建議,幫助開發(fā)者編寫更健壯的JavaScript代碼,需要的朋友可以參考下
在JavaScript中,類型判斷有多種方法,各有優(yōu)缺點。以下是全面的類型判斷指南:
1.typeof 操作符
最基本的類型判斷,適用于原始類型:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof 123n // "bigint"
typeof function(){} // "function"
// 局限性:
typeof null // "object" (歷史遺留問題)
typeof [] // "object"
typeof {} // "object"
typeof new Date() // "object"2.instanceof 操作符
檢查對象是否是特定構(gòu)造函數(shù)的實例:
[] instanceof Array // true new Date() instanceof Date // true [] instanceof Object // true (原型鏈上) // 局限性: "hello" instanceof String // false 123 instanceof Number // false
3.Object.prototype.toString.call()
最可靠的類型判斷方法:
Object.prototype.toString.call("hello") // "[object String]"
Object.prototype.toString.call(42) // "[object Number]"
Object.prototype.toString.call(123n) // "[object BigInt]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(new Date()) // "[object Date]"
Object.prototype.toString.call(/regex/) // "[object RegExp]"
Object.prototype.toString.call(function(){})// "[object Function]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"4.專用判斷方法
數(shù)組判斷
Array.isArray([]) // true (ES5+,最可靠)
[] instanceof Array // true
Object.prototype.toString.call([]) === '[object Array]' // true
// 舊瀏覽器兼容方法
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}NaN 判斷
isNaN(NaN) // true (有問題:會嘗試轉(zhuǎn)換類型)
isNaN("hello") // true
Number.isNaN(NaN) // true (ES6,推薦)
Number.isNaN("hello") // false
// 替代方案:
function isNaN(value) {
return value !== value; // NaN是唯一不等于自身的值
}空值判斷
// 嚴格相等判斷
value === null // 判斷null
value === undefined // 判斷undefined
// 雙等號判斷(可能產(chǎn)生意外轉(zhuǎn)換)
value == null // true if value is null or undefined
// 安全檢查
if (value != null) {
// value既不是null也不是undefined
}5.實用類型判斷函數(shù)
// 獲取準確類型
function getType(value) {
return Object.prototype.toString.call(value)
.replace(/^\[object (\w+)\]$/, '$1')
.toLowerCase();
}
// 類型判斷工具函數(shù)
const TypeChecker = {
isString: val => typeof val === 'string',
isNumber: val => typeof val === 'number' && !isNaN(val),
isBoolean: val => typeof val === 'boolean',
isUndefined: val => val === undefined,
isNull: val => val === null,
isObject: val =>
val !== null && typeof val === 'object' && !Array.isArray(val),
isArray: val => Array.isArray(val),
isFunction: val => typeof val === 'function',
isDate: val => val instanceof Date,
isRegExp: val => val instanceof RegExp,
isError: val => val instanceof Error,
isSymbol: val => typeof val === 'symbol',
isBigInt: val => typeof val === 'bigint',
isPromise: val =>
Boolean(val && typeof val.then === 'function'),
// 判斷原始類型
isPrimitive: val =>
val === null ||
typeof val === 'string' ||
typeof val === 'number' ||
typeof val === 'boolean' ||
typeof val === 'undefined' ||
typeof val === 'symbol' ||
typeof val === 'bigint',
// 判斷類數(shù)組對象(有l(wèi)ength屬性)
isArrayLike: val =>
val != null &&
typeof val !== 'function' &&
typeof val.length === 'number'
};
// 使用示例
TypeChecker.isArray([1, 2, 3]) // true
TypeChecker.isObject({ a: 1 }) // true
TypeChecker.isPrimitive(42) // true6.ES6+ 新增方法
// Number類型判斷 Number.isInteger(42) // true Number.isInteger(42.0) // true Number.isInteger(42.5) // false Number.isSafeInteger(42) // true // 數(shù)組類型判斷 Array.isArray([]) // true // Symbol類型 typeof Symbol() === 'symbol' // BigInt類型 typeof 123n === 'bigint'
7.特殊情況的處理
// 判斷是否為純對象(排除數(shù)組、函數(shù)等)
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]' &&
Object.getPrototypeOf(obj) === Object.prototype;
}
// 判斷是否為DOM元素
function isElement(obj) {
return !!(obj && obj.nodeType === 1);
}
// 判斷是否為空對象
function isEmptyObject(obj) {
return isPlainObject(obj) && Object.keys(obj).length === 0;
}
// 判斷是否為數(shù)值(包括字符串數(shù)字)
function isNumeric(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
}8.最佳實踐建議
- 基礎類型判斷:使用
typeof - 數(shù)組判斷:使用
Array.isArray() - null判斷:使用
value === null - 復雜類型判斷:使用
Object.prototype.toString.call() - 構(gòu)造函數(shù)實例判斷:使用
instanceof - NaN判斷:使用
Number.isNaN() - 類型安全比較:優(yōu)先使用
===而不是==
9.TypeScript中的類型判斷
// 類型守衛(wèi)
function isString(value: any): value is string {
return typeof value === 'string';
}
// 使用示例
function process(value: string | number) {
if (isString(value)) {
// TypeScript知道這里是string類型
console.log(value.toUpperCase());
}
}選擇哪種方法取決于具體需求,但掌握這些技術(shù)可以幫助你編寫更健壯的JavaScript代碼。
以上就是JavaScript類型判斷的多種方法的詳細內(nèi)容,更多關(guān)于JavaScript類型判斷方法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
javascript仿php的print_r函數(shù)輸出json數(shù)據(jù)
輸出json數(shù)據(jù),php的print_r函數(shù)可以輕松實現(xiàn),下面為大家介紹下javascript也可以模仿print_r函數(shù)輸出json數(shù)據(jù),具體實現(xiàn)如下,感興趣的朋友可以了解下2013-09-09
js定時調(diào)用方法成功后并停止調(diào)用示例
這篇文章主要介紹了js定時調(diào)用方法成功后并停止調(diào)用的實現(xiàn),需要的朋友可以參考下2014-04-04
javascript實現(xiàn)智能手環(huán)時間顯示
這篇文章主要為大家詳細介紹了javascript實現(xiàn)智能手環(huán)時間顯示,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09

