眾所周知,js有7種數據類型
1. null
2. undefined
3. boolean
4. number
5. string
6. object
7. symbol
但是在實際的開發種,需要我們去判斷數據類型。尤其是判斷Array、Object、function 、( Symbol)。
第一種方式: typeof
typeof null ---> "object"
typeof undefined ---> "undefined"
typeof true | false ---> 'boolean'
typeof 42 ---> 'number'
typeof "42" ---> 'string'
typeof { name : '1'} | [] ---> 'object'
typeof Symbol ---> 'symbol'
typeof ()=>{} ---> 'function'
typeif void 0 ---> 'undefined'
第二種方式 instanceof 但是這種方式只適合判斷object類型
比如 : var arr = [] ; arr instanceof Array ---> true
null instanceof Object ---> false
[function] instanceof Object | Function --> true
第三種方式 Object.prototype.toString.call() 這種方式可以將全部的數據類型檢測出來 也是 推薦的方式
因為toString是Object的原型方法, 而 Array Function 等都是Object的實例。都重寫了toString 方法。返回的是類型的字符串
Object.prototype.toString.call(null) ---> [object Null]
Object.prototupe.toString.call(undefined) ---> [object Undefined]
Object.prototype.toString.call(123) ---> [object Number]
Object.prototype.toString.call(true) ---> [object Boolean]
Object.prototype.toString.call('123') ---> [object String]
Object.prototype.toString.call({}) ---> [object Object]
Object.prototype.toString.call([]) ---> [object Array]
Object.prototype.toString.call(Math) ---> [object Math]
Object.prototype.toString.call(function(){}) ---> [object Function]
Objdec.prototype.toString.call(new Date) ---> [object Date]
Object.prototype.toString.call(Symbol()) ---> [object Symbol]
第四種方式: constructor 判斷對象的構造函。
1. null 是js 原型鏈的起點,沒有構造函數
2. undefined 沒有構造函數
3. [].constructor === Array ---> true
4. [string].constructor === String
5. [object].constructor === object
6. [number].constructor === Number
7. [symbol].constructor === Symbol
8. [function].constructor === Function
9. [new Date].constructor === Date
10. [RegExp].constructor === RegExp
需要注意的是 Math 沒有構造函數 Math的構造函數在 Object上 所以不適用 constructor 方法