js 里判斷變量類型大概分為三種方法
1. typeof 比較常用的
先排除幾個特殊情況,之后的邏輯可能就能清晰點如下
1 // 特殊的基本數據類型判斷 2 typeof null // 'object' 3 // 特殊的引入數據類型判斷 4 typeof function () {} // 'function' 5 typeof new Function() // 'function'
剩下的就是基本數據類型會返回其數據類型,其他引用數據類型包括 new 關鍵字定義的變量,如下
1 // 基本數據類型判斷 2 typeof 1 // 'number' 3 typeof 'a' // 'string' 4 typeof false // 'boolean' 5 typeof undefined // 'undefined' 6 typeof Symbol() // 'symbol' 7 8 // 引用數據類型判斷和new關鍵字創建的變量判斷類型 9 typeof {} // 'object' 10 typeof [] // 'object' 11 typeof new Number(1) // 'object' 12 typeof new String('a') // 'object' 13 typeof new Boolean(true) // 'object' 14 typeof new Number(1) // 'object' 15 typeof new Date() // 'object' 16 function Car () {} // 定義一個構造函數 17 typeof new Car() // 'object'
2, instanceof 該方法是用來判斷變量的原型鏈上層有沒有等號右邊的構造函數,不適用基本數據類型判斷(number, string, boolean),如下
1 function Car () {} // 定義一個構造函數 2 console.log(new Car() instanceof Car) 3 console.log({} instanceof Object) // true 4 console.log([] instanceof Array) // true 5 console.log(new String('') instanceof String) // true 6 console.log('' instanceof String) // false
3. Object.prototype.toString.call() 剛知道這個方法,使用之后覺得還是很棒的
js 內置的數據類型和內置的對象都能判斷出其類型,自定義的構造函數返回的是 [object Object]
1 Object.prototype.toString.call(null) // [object Null] 2 Object.prototype.toString.call(undefined) // [object Undefined] 3 Object.prototype.toString.call(1) // [object Number] 4 Object.prototype.toString.call(new Number(1)) // [object Number] 5 Object.prototype.toString.call('a') // [object String] 6 Object.prototype.toString.call(new String('a')) // [object String] 7 8 Object.prototype.toString.call({}) // [object Object] 9 Object.prototype.toString.call([]) // [object Array] 10 Object.prototype.toString.call(new Date()) // [object Date] 11 Object.prototype.toString.call(/^d$/g) // [object RegExp] 12 Object.prototype.toString.call(() => {}) // [object Function] 13 Object.prototype.toString.call(new Function()) // [object Function] 14 15 function Car () {} // 定義一個構造函數 16 Object.prototype.toString.call(new Car()) // [object Object]
以上