JavaScript 精確 判斷 資料型別
阿新 • • 發佈:2018-11-10
一、使用 typeof
typeof 返回對數的型別
typeof 123 == 'number'
typeof '123' == 'string'
typeof [1,2,3] == 'object'
typeof {a:1} == 'object'
typeof null == 'object'
typeof function(){} == 'function'
typeof true == 'boolean'
typeof undefined = 'undefined'
結論:typeof 不能用來判斷資料是 陣列、物件 或者是 null
二、使用 instanceof
暫且不談
三、使用 Object.prototype.toString.call()
Object.prototype.toString.call(123) == '[object Number]' Object.prototype.toString.call('123') == '[object String]' Object.prototype.toString.call(true) == '[object Boolean]' Object.prototype.toString.call(function(){}) == '[object Function]' Object.prototype.toString.call([1,2,3]) == '[object Array]' Object.prototype.toString.call({a:1}) == '[object Object]' Object.prototype.toString.call(null) == '[object Null]' Object.prototype.toString.call(undefined) == '[object Undefined]'
所以,該用那個呢 ? 不需要在說了吧。
所以,該用 Object.prototype.toString.call() ............
var data = '' // 一個你需要驗證的資料
Object.prototype.toString.call(data).slice(8,this.length-1) // 返回的值,就是 data 的資料型別