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() |
| 是否是 NaN | Number.isNaN() |
| 是否是基本类型 | typeof够用 |
| 是否是某个类的实例 | instanceof |
| 要绝对准确 | Object.prototype.toString.call() |
最常见的错误就是用typeof判断数组和null,记住这两个坑就够了。
