判断数据类型方法汇总

128 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

判断数据类型的几种方法

  1. 使用typeof()判断数据类型
typeof 'a'; // string 有效
typeof 1; // number 有效
typeof true; //boolean 有效
typeof Symbol(); // symbol 有效
typeof undefined; //undefined 有效
typeof new Function(); // function 有效
typeof null; //object 无效
typeof [1] ; //object 无效
typeof new RegExp(); //object 无效
typeof new Date(); //object 无效

typeof判断基本类型除了null外都能返回正确结果,引用类型除了function外,一律返回object其中,null 有属于自己的数据类型 Null ,引用类型中的数组、日期、正则 也都有属于自己的具体类型,而 typeof 对于这些类型的处理,只返回了处于其原型链最顶端的 Object 类型

  1. 使用instanceof操作符判断数据类型
[] instanceof Array; // true
new Date() instanceof Date;// true
function Person(){};
new Person() instanceof Person;//true
[] instanceof Object; // true
new Date() instanceof Object;// true
new Person instanceof Object;// true

从原型链可以看出,[]__proto__ 直接指向Array.prototype,间接指向 Object.prototype,所以按照 instanceof 的判断规则,[] 就是Object的实例。依次类推,类似的 new Date()new Person() 也会形成一条对应的原型链 。   因此,instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类

  1. 使用对象的constructor属性判断数据类型
a.constructor == String // true
new Number(1).constructor == Number // true
true.constructor == Boolean // true
new Function().constructor == Function // true
new Date().constructor == Date // true
new Error().constructor == Error // true
[].constructor == Array // true

1. nullundefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。

 2. 函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object

  1. 使用Array.isArray()检验是否为数组
 Array.isArray([1,2]) // true

Array.isArray() 本质上检测的是对象的 [[Class]]

  1. 使用isNaN()判断是否为非数字类型
 isNaN(123) // false
 isNaN('123') // false
 isNaN('ab') // true
  1. 使用toString()方法检验对象类型
 Object.prototype.toString.call('') ;   // [object String]
 Object.prototype.toString.call(1) ;    // [object Number]
 Object.prototype.toString.call(true) ; // [object Boolean]
 Object.prototype.toString.call(Symbol()); //[object Symbol]
 Object.prototype.toString.call(undefined) ; // [object Undefined]
 Object.prototype.toString.call(null) ; // [object Null]
 Object.prototype.toString.call(new Function()) ; // [object Function]
 Object.prototype.toString.call(new Date()) ; // [object Date]
 Object.prototype.toString.call([]) ; // [object Array]
 Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
 Object.prototype.toString.call(new Error()) ; // [object Error]
 Object.prototype.toString.call(document) ; // [object HTMLDocument]
 Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

toString()Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]]