检查数据类型的方法

156 阅读1分钟

1. 判断数据类型的方法

基本类型:String、Number、Boolean、Symbol、Undefined、Null 

引用类型:Object、Function、Array、RegExp、Date 

①:typeof

typeof ''; // string 有效

typeof 1; // number 有效

typeof Symbol(); // symbol 有效

typeof true; //boolean 有效

typeof undefined; //undefined 有效

typeof null; //object 无效

typeof [] ; //object 无效

typeof new Function(); // function 有效

typeof new Date(); //object 无效

typeof new RegExp(); //object 无效

②:instanceof

instanceof 检测的是原型

③:constructor

image.png

④: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 的引用