js中的資料型別,以及如何檢測資料型別
阿新 • • 發佈:2019-08-28
基本資料型別: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]"
&n