The order from the most garbage way to the most powerful way is: type of > constructor > instance of > toString
1.typeof
The detection object type is too fuzzy, and function, object and array types will return object, so this method is garbage, but it has strong practicability and gas field
2.constructor
Constructor of the instance object (instance object. constructor). Return the constructor to distinguish the type
var str = 'abc'; var num = 100; var arr = new Array(); var date = new Date(); alert(str.constructor); alert(num.constructor); alert(arr.constructor); alert(date.constructor);
3.instanceof
Determine whether an object is an instance of a constructor (class). Note that this method can only detect instance objects. Return Boolean
var str=new String('abc'); var num=new Number(100); var arr=new Array(); var date=new Date(); alert(str instanceof String); alert(num instanceof Number); alert(arr instanceof Array); alert(date instanceof Date); alert(str instanceof Object);
4.toString()
This is the most powerful five-star method. It can be used to convert not only base but also string
console.log(Object.prototype.toString.call(5).slice(8,-1)); console.log(Object.prototype.toString.call('abc').slice(8,-1)); console.log(Object.prototype.toString.call(true).slice(8,-1)); console.log(Object.prototype.toString.call(function(){}).slice(8,-1)); console.log(Object.prototype.toString.call([]).slice(8,-1)); console.log(Object.prototype.toString.call({}).slice(8,-1)); console.log(Object.prototype.toString.call(/\d/g).slice(8,-1)); console.log(Object.prototype.toString.call(new Date).slice(8,-1)); console.log(Object.prototype.toString.call(null).slice(8,-1)); console.log(Object.prototype.toString.call(undefined).slice(8,-1)); console.log(Object.prototype.toString.call(Math).slice(8,-1));
// Number // String // Boolean // Function // Array // Object // RegExp // Date // Null // Undefined // Math