基本數據類型:string,number,boolean,null,undefined,symbol
引用數據類型:object(array,function...)
常用的檢測數據類型的方法一般有以下三種:
1.typeof 一般主要用來檢測基本數據類型,因為它檢測引用數據類型返回的都是object
還需要注意的一點是:typeof檢測null返回的也是object(這是JS一直以來遺留的bug)
typeof 1 "number" typeof 'abc' "string" typeof true "boolean" typeof null "object" typeof undefined "undefined" typeof {} "object" typeof [] "object"
2.instanceof 這個方法主要是用來准確地檢測引用數據類型(不能用來檢測基本數據類型)
function add(){} add instanceof Function //true var obj = {} obj instanceof Object //true [] instanceof Array //true
3.Object.prototype.toString() 可以用來准確地檢測所有數據類型
Object.prototype.toString.call([]) //"[object Array]" Object.prototype.toString.call(1) //"[object Number]" Object.prototype.toString.call(null) //"[object Null]" Object.prototype.toString.call(undefined) //"[object Undefined]" Object.prototype.toString.call(true) //"[object Boolean]" Object.prototype.toString.call('111') //"[object String]" Object.prototype.toString.call({}) //"[object Object]" Object.prototype.toString.call(function add(){}) //"[object Function]"