在js中,有5中基本數(shù)據(jù)類型和1種復(fù)雜數(shù)據(jù)類型
基本數(shù)據(jù)類型:Underfined,Null,Boolean,String,Number
復(fù)雜數(shù)據(jù)類型:Object,包含Array,Function,Data...
1、使用typeof檢測(cè)
可以檢測(cè):number,string,boolean,function,undefined
不可以檢測(cè): array,json,null,date,regex,error只能被檢測(cè)出object,
2、使用instanceof檢測(cè)
可以檢測(cè): Array,Object,Function,Date,RegExp,Error,
不可以檢測(cè)基本數(shù)據(jù)類型:Number,String,Boolean,Undefined, Null
但是使用這種方式創(chuàng)建變量就可以
const num = new Number(123);
const str = new String('1234');
const bool = new Boolean(false);
3、使用constructor檢測(cè)
constructor是原型對(duì)象上的屬性,指向構(gòu)造函數(shù)。
const num = 123;
num.constructor => function Number() {[native code]}
所以可以使用 num.constructor === Number
不可以檢測(cè):undefined,null
缺點(diǎn): 實(shí)例的constructor屬性可以被修改,會(huì)導(dǎo)致檢測(cè)出的結(jié)果不正確
4、使用Object.prototype.toString.call
使用方式:
Object.prototype.toString.call(num) => '[object Number]'
...
可檢測(cè)所有數(shù)據(jù)類型
所以可以使用Object.prototype.toString.call(num) === '[object Number]'