本文已参与「新人创作礼」活动,一起开启掘金创作之路。
判断数据类型的几种方法
- 使用
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类型
- 使用
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只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类
- 使用对象的
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 // true1.
null和undefined是无效的对象,因此是不会有constructor存在的,这两种类型的数据需要通过其他方式来判断。2. 函数的
constructor是不稳定的,这个主要体现在自定义对象上,当开发者重写prototype后,原有的constructor引用会丢失,constructor会默认为Object
- 使用
Array.isArray()检验是否为数组
Array.isArray([1,2]) // true
Array.isArray()本质上检测的是对象的[[Class]]值
- 使用
isNaN()判断是否为非数字类型
isNaN(123) // false
isNaN('123') // false
isNaN('ab') // true
- 使用
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]]