標籤:
通常為了快捷我們都會使用 typeof 操作符去判斷變數的類型,但是這種做法不能準確判斷出變數的類型。
比如:
typeof []; // 返回 ‘object‘typeof {}; // 返回 ‘object‘typeof new Number(1); // 返回 ‘object‘typeof new Array(‘a‘, ‘b‘); // 返回 ‘object‘
typeof new String(‘abc‘); // 返回 ‘object‘
typeof new Function(); // 返回 ‘function‘
typeof 操作符在判斷 new 出來的對象時除了 new Function 其他通常返回 ‘object‘。
因此為了能準確判斷類型,我們找到了一個更好的方法就是通過 call 調用 Object 原型上的 toString 方法來擷取變數的具體類型。
Object.prototype.toString.call( obj );
我看了下jquery裡面的用來判斷變數類型的 type 函數,實現得相對複雜。
其用法類似是這樣的:
var abc = ‘abc‘;if( jQuery.type( abc ) === ‘string‘ ) { //是字元類型的話就執行這裡}else{ //不是就執行這裡}
jQuery.type 函數最終返回傳進去變數的類型,還需要我們通過運算子比較來判斷。
覺得有些多餘,不如像下面這樣來的方便快捷:
var abc = ‘abc‘;if( isType(abc, ‘string‘) ) { //true}else{ //false}
isType 函數接受一個字串參數,直接返回 true 還是 false。
我是這樣實現的:
function isType( obj, type ) { var toStr = Object.prototype.toString; var toLower = toStr.call( obj ).toLowerCase(); return toLower.indexOf( ‘[object ‘ + type + ‘]‘ ) !== -1;}
還有一個通過正則來實現的版本:
function isType( obj, type ) { var toStr = Object.prototype.toString.call( obj ); return (new RegExp(‘\\[object ‘ + type + ‘\\]‘ , "i")).test( toStr );}
在javascript裡類型判斷非常常用,於是我把這個函數直接添加到 Object.prototype 上,這樣的話每個變數都能繼承這個函數了。
Object.prototype.isType = function( type ) { var toStr = Object.prototype.toString; var toLower = toStr.call( this ).toLowerCase(); return toLower.indexOf( ‘[object ‘ + type + ‘]‘ ) !== -1;};
這樣加上去的話就方便多了:
‘abc‘.isType( ‘string‘ ) // 返回true‘abc‘.isType( ‘number‘ ) // 返回false[‘a‘, ‘b‘, ‘c‘].isType( ‘array‘ ) // 返回true[‘a‘, ‘b‘, ‘c‘].isType( ‘string‘ ) // 返回false(123).isType( ‘number‘ ) // 返回true(123).isType( ‘string‘ ) // 返回falsenew Date().isType( ‘date‘ ) // 返回truenew Date().isType( ‘number‘ ) // 返回false
javascript類型判斷