JavaScript :检验数据类型的方法

JavaScript :检验数据类型的方法

JavaScript 检验数据类型的方法整理

方法适用场景准确度示例
typeof基础类型(string/number/boolean/undefined/symbol/bigint/function)⭐⭐⭐typeof null === 'object'
instanceof引用类型(对象/数组/函数/正则等)⭐⭐⭐⭐[] instanceof Array
Object.prototype.toString.call()所有类型,最准确⭐⭐⭐⭐⭐终极方案
constructor通过构造函数判断⭐⭐⭐可被篡改
Array.isArray()专门检测数组⭐⭐⭐⭐⭐推荐替代instanceof Array
Number.isNaN()专门检测 NaN⭐⭐⭐⭐⭐优于全局isNaN()
Number.isFinite()检测有限数⭐⭐⭐⭐⭐优于全局isFinite()
Number.isInteger()检测整数⭐⭐⭐⭐⭐-

1.typeof— 最常用但有坑

typeof "hello" // "string" typeof 123 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof Symbol() // "symbol" typeof 10n // "bigint" typeof function(){} // "function" typeof null // "object" ❌ 经典 Bug typeof [] // "object" typeof {} // "object"

核心问题null和数组、对象都返回"object",无法区分。

2.instanceof— 检测引用类型

[] instanceof Array // true /abc/ instanceof RegExp // true function f(){} instanceof Function // true // ❌ 跨 iframe/window 会失效 // ❌ 无法检测基本类型

3.Object.prototype.toString.call()— 终极方案 ✅

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(/abc/) // "[object RegExp]" Object.prototype.toString.call(() => {}) // "[object Function]" Object.prototype.toString.call(123) // "[object Number]" Object.prototype.toString.call("abc") // "[object String]" Object.prototype.toString.call(true) // "[object Boolean]"

这是唯一能准确区分null和所有其他类型的方法。

4. 专用方法(ES6+ 推荐)

Array.isArray([]) // true ✅ 优先用这个 Number.isNaN(NaN) // true ✅ 全局 isNaN("abc") 也返回 true,这个不会 Number.isFinite(123) // true Number.isInteger(123.0) // true Number.isSafeInteger(9007199254740991) // true

实战推荐:封装一个万能判断

function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } getType(null) // "Null" getType([]) // "Array" getType({}) // "Object" getType(123) // "Number" getType("abc") // "String" getType(/abc/) // "RegExp"

选型建议

你要判断什么用什么
是否是数组Array.isArray()
是否是 NaNNumber.isNaN()
是否是基本类型typeof够用
是否是某个类的实例instanceof
要绝对准确Object.prototype.toString.call()

最常见的错误就是用typeof判断数组和null,记住这两个坑就够了。