Home >Web Front-end >JS Tutorial >4 methods for js data type detection
1.typeof
Disadvantages: It is not very convenient to detect types such as null and Array
Js code
typeof null; //"object"
typeof []; //"object"
2.instanceof
Disadvantages: 1. Only applicable to object types
2. As long as the current class is on the prototype chain of the instance, the detected results are true
Js code
123 instanceof Number; //false
null instanceof null; //TypeError
null instanceof Object; //false
function A(){}
function B(){}
A.prototype=new B();
var aObj=new A() ;
aObj instanceof B;//true
aObj instanceof A;//true
3.constructor
Note: An error will occur during class inheritance
Js code
function A(){};
function B(){};
A.prototype = new B();
var aObj = new A();
aObj.constructor === B; //true;
aObj.constructor === A; //false;
4. Custom method implementation (more general)
Js code
function getType(o){
return Object.prototype.toString.call(o).slice(8,-1 ;
getType({}); //"Object"
getType(()=>{}); //"Function"
getType(document.createElement('div')); //"HTMLDivElement"