JavaScript :检验数据类型的方法 JavaScript 检验数据类型的方法整理方法适用场景准确度示例typeof基础类型string/number/boolean/undefined/symbol/bigint/function⭐⭐⭐typeof null object❌instanceof引用类型对象/数组/函数/正则等⭐⭐⭐⭐[] instanceof Array✅Object.prototype.toString.call()所有类型最准确⭐⭐⭐⭐⭐终极方案constructor通过构造函数判断⭐⭐⭐可被篡改Array.isArray()专门检测数组⭐⭐⭐⭐⭐推荐替代instanceof ArrayNumber.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记住这两个坑就够了。