在JS中有時候是須要對一個變量進行檢測的,檢測到這個變量是什麼類型以後,咱們就能夠作相應的處理。javascript
方法一typeofjava
typeof方法主要用於基本類型的檢測,在檢測Boolean,number,undefined,string的時候很是好用。好比:spa
1 var test1= 1; 2 alert(typeof test1);//輸出number
3 var test2 = ""; 4 alert(typeof test2);//輸出string
5 var test3 = undefined; 6 alert(typeof test3);//輸出undefined
7 var test4 = true; 8 alert(typeof test4);//輸出boolean
可是用typeof來檢測引用類型的時候就沒有那麼好用了。由於不管你怎麼檢測,輸出都是object類型。這個時候就要用到Object.prototype.toString方法或者instancof。prototype
方法二instanceofcode
var test1 = new Array();
alert(test1 instanceof Array);//輸出true
var test2 = new String();
alert(test2 instanceof String);//輸出true
var test3 = {};
alert(test3 instanceof Object);//輸出true
var test4 = /qwe/;
alert(test4 instanceof RegExp);//輸出true
var test5 = 1;
alert(test5 instanceof number);//輸出false
var test6 = "";
alert(test6 instanceof String);//輸出false
var test7 = true;
alert(test7 instanceof Boolean);//輸出false
instanceof方法對於引用類型很好用,能完全檢測出是什麼類型的引用,可是相似於typeof,instanceof對於基本類型就很差用了,結果都會輸出false。blog
方法三Object.prototype.toString.callip
這個方法就是基於上面兩個方法的取其精華,去其糟粕而生成的。string
var test1 = new Array(); alert(Object.prototype.toString.call(test1));//輸出object Array
var test2 = new String(); alert(Object.prototype.toString.call(test2));//輸出object String
var test3 = {}; alert(Object.prototype.toString.call(test3));//輸出object Object
var test4 = /qwe/; alert(Object.prototype.toString.call(test4));//輸出object RegExp
var test5 = 1; alert(Object.prototype.toString.call(test5));//輸出object Number
var test6 = ""; alert(Object.prototype.toString.call(test6));//輸出object String
var test7 = true; alert(Object.prototype.toString.call(test7));//輸出object Boolean
結合以上3種方法,能夠對變量作很完全的類型檢測。class