多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
常用的判断JS数据类型的方法有以下四种: ### **typeof**: 返回一个表示数据类型的字符串。 ``` typeof ''; // string 有效 typeof 1; // number 有效 typeof true; //boolean 有效 typeof undefined; //undefined 有效 typeof null; //object 无效 typeof [] ; //object 无效 typeof new Date(); //object 无效 typeof new RegExp(); //object 无效 typeof console.log; // function 有效 typeof Symbol(); // symbol 有效 ``` **说明:** * 数组和对象返回的都是object,不能用typeof做区分。 ### **instanceof**: 用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。简言之, A instanceof B表示如果A是B的实例,则返回true,否则返回false。 ``` [] instanceof Array; //true {} instanceof Object; //true null instanceof Object; //false null instanceof Array; //false ``` **说明:** * 对于基本数据类型,字面量方式创建出来的结果和实例方式创建的是有一定的区别的: ``` console.log(1 instanceof Number) //false console.log(new Number(1) instanceof Number) //true ``` * 只要在当前实例的原型链上,我们用其检测出来的结果都是true: ``` var arr = [1, 2, 3]; console.log(arr instanceof Array) // true console.log(arr instanceof Object); // true ``` * 由于浏览器对于特殊数据类型null和undefined的限制作用,无法使用instanceof进行判断。 ### **constructor**:功能和instanceof类似,但是可以用于判断基本数据类型。 ``` let a = 1, b = '', c = {}, d = []; a.constructor: ƒ Number() { [native code] } b.constructor: ƒ String() { [native code] } c.constructor: ƒ Object() { [native code] } d.constructor: ƒ Array() { [native code] } ``` **说明:** * null和undefined是比较特殊的基本数据类型,不存在constructor,无法通过此方法进行判断: ![](https://img.kancloud.cn/0a/ef/0aefd746d0a7026c46005491e1a85a81_830x151.png) ### **Object.prototype.toString.call()** ``` Object.prototype.toString.call('') ; // [object String] Object.prototype.toString.call(1) ; // [object Number] Object.prototype.toString.call(true) ; // [object Boolean] Object.prototype.toString.call(undefined) ; // [object Undefined] Object.prototype.toString.call(null) ; // [object Null] 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 Window] window是全局对象global的引用 ```