JS类型判断全解析:typeof、instanceof、toString、Array.isArray一网打尽!

184 阅读2分钟

你是否在使用JS的过程中遇到过这样的疑惑:

  • typeof null 为什么是 object
  • 怎么判断一个变量到底是不是数组?
  • instanceoftypeof 到底有什么区别?
    类型判断看似简单,实则暗藏玄机。今天就带你用最通俗的方式,彻底搞懂JS里的各种类型判断方法!

一、typeof:最常用也最容易踩坑的类型判断

基本用法

console.log(typeof 'hello'); // string
console.log(typeof 123); // number
console.log(typeof false); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (坑点)
console.log(typeof Symbol(1)); // symbol
console.log(typeof 123n); // bigint
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof function(){}); // function

原理简析

  • typeof 是通过将值转换成二进制来判断类型的,前三位为0的都识别为object。
  • null的二进制全是0,所以typeof null === 'object'。

常见错误与解决

  • 误区:typeof 不能区分数组、对象、null。
  • 实用技巧:判断引用类型时需配合其他方法。

二、instanceof:判断引用类型的利器

基本用法

console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log(function(){} instanceof Function); // true
console.log(new Date() instanceof Date); // true
console.log([] instanceof Object); // true

不能判断基本类型

console.log('hello' instanceof String); // false
console.log(123 instanceof Number); // false

原理图解与手写实现

  • instanceof 通过遍历对象的原型链,查找右侧构造函数的 prototype。
  • 代码演示:
function myInstanceOf(L, R) {
    L = L.__proto__;
    while(L) {
        if (L === R.prototype) return true;
        L = L.__proto__;
    }
    return false;
}
console.log(myInstanceOf([], Array)); // true

常见错误

  • 不能判断基本类型(因为没有原型链)。
  • 仅适用于对象类型。

三、Object.prototype.toString.call:最精确的类型判断

基本用法

console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call('hello')); // [object String]

原理简析

  • 内部通过[[Class]]属性返回类型字符串。
  • 能精确区分所有内置类型,包括null、undefined、数组、正则等。

实用技巧

  • 获取类型字符串后可用.slice(8, -1)提取类型名。

四、Array.isArray:判断数组的最佳实践

用法

console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false
  • 兼容性好,推荐判断数组类型时优先使用。

五、常见类型判断误区与面试高频问题

  • typeof null 为什么是 object
  • 如何判断一个变量是数组?
  • instanceof 能判断基本类型吗?
  • Object.prototype.toString.call 能判断自定义类型吗?

六、总结

本文带你系统梳理了JS类型判断的四大方法及其原理、优缺点和常见误区。