數據類型檢測方法

typeof

typeof操做符是檢測基本類型的最佳工具。數組

"undefined" — 未定義 typeof unddfined
"boolean"   — 布爾值 typeof boolean
"string"    — 字符串 typeof string
"number"    — 數值 typeof unddfined number
"object"    — 對象或null  typeof object/null
"function"  — 函數 typeof function
複製代碼

Instanceof

instanceof用於檢測引用類型,能夠檢測到它是什麼類型的實例。
instanceof 檢測一個對象A是否是另外一個對象B的實例的原理是:查看對象B的prototype指向的對象是否在對象A的[[prototype]]鏈上。若是在,則返回true,若是不在則返回false。不過有一個特殊的狀況,當對象B的prototype爲null將會報錯(相似於空指針異常).bash

var sXzaver = new String("Xzavier"); 
console.log(sXzaver instanceof String);   //  "true"
var aXzaver = [1,2,3]; 
console.log(aXzaver instanceof Array);   //  "true"
檢測數組在ECMA Script5中定義了一個新方法Array.isArray()
複製代碼

Constructor

constructor屬性返回對建立此對象的數組函數的引用。能夠用於檢測自定義類型函數

'xz'.constructor == String // true
(123).constructor == Number // true
(true).constructor == Boolean // true
[1,2].constructor == Array // true
({name:'xz'}).constructor == Object // true
(function(){}).constructor == Function // true
(new Date()).constructor == Date // true
(Symbol()).constructor == Symbol // true
(/xz/).constructor == RegExp // true
複製代碼

constructor不適用於null和undefined。除了這些原生的,constructor還可驗證自定義類型。工具

function Xzavier(){}
var xz = new Xzavier();
xz.constructor == Xzavier;  // true 
複製代碼

Object.prototype.toString.call(obj)

推薦使用:Object.prototype.toString.call(obj)ui

原理:調用從Object繼承來的原始的toString()方法

Object.prototype.toString.call('xz'); //"[object String]"
Object.prototype.toString.call(123);  //"[object Number]"
Object.prototype.toString.call(true); //"[object Boolean]"
Object.prototype.toString.call([1,2]); //"[object Array]"
Object.prototype.toString.call({name:'xz'}); //"[object Object]"
Object.prototype.toString.call(function(){}); //"[object Function]"
Object.prototype.toString.call(null); //"[object Null]"
Object.prototype.toString.call(undefined); //"[object Undefined]"
Object.prototype.toString.call(); //"[object Undefined]"
Object.prototype.toString.call(new Date()); //"[object Date]"
Object.prototype.toString.call(/xz/);  //"[object RegExp]"
Object.prototype.toString.call(Symbol()); //"[object Symbol]"

var obj = {name:"Xzavier", age:23};
var a = [1,2,3];

function isType(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}
isType(obj);  // "Object" 
isType(a)  // "Array"  
複製代碼
相關文章
相關標籤/搜索