記得很久之前拢蛋,有簡單的記錄過 js 中的數據類型(點這里)楞遏。那么,如何去判斷一個變量的數據類型呢塌碌?
先來看看一些判斷 bug :
typeof null // "object"
typeof new String('abc') // "object"
var iframeArr = new window.frames[0].Array;
iframeArr instanceof Array // false
isNaN('abc') // true
所以說渊胸,在判斷類型的時候,往往不小心就產生了 bug . 那么台妆,怎樣才能準確判斷數據類型翎猛?來看看 undescore.js
和 jQuery
的做法。
1. underscore 1.8.3
underscore 提供了一堆判斷類型的函數接剩,如下:
- isArray
- isObject
- isArguments
- isFunction
- isString
- isNumber
- isFinite
- isBoolean
- isDate
- isRegExp
- isNaN
- isNull
- isUndefined
其核心的判斷代碼如下切厘,利用 Object.prototype.toSting
,這個也是業(yè)界公認好用的方法:
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
下面看看其他判斷函數懊缺。
- isArray
先判斷瀏覽器是否支持原生ES5的 Array.isArray
方法疫稿,支持則直接用原生方法判斷培他,不然利用 Object.prototype.toSting
來判斷。
var ObjProto = Object.prototype,
toString = ObjProto.toString,
nativeIsArray = Array.isArray;
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
- isObject
直接用 typeof 判斷遗座。不過判斷函數的時候舀凛,也是 true
? 這樣豈不是會和 isFunction
有重疊?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// example
function a () {}
console.log(_.isObject(a)); // true
- isArguments 低于IE9 版本
直接判斷是否有 callee
屬性途蒋。要注意的是:在 ES5 標準中猛遍,嚴格模式下,函數參數是沒有 callee
屬性的号坡,詳細看這里懊烤。
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// 在 IE < 9 是沒有 [object Arguments] 這個類型的
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
- isFunction 優(yōu)化版本
這里會有疑問,明明直接用 typeof 判斷就可以了宽堆,為什么還要加后面的 || false
腌紧?注釋里說是因為 IE11 (& IE8) 下面的 bug。詳情看這里畜隶。
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
- isFinite
判斷一個數是否為有限壁肋,先看基本的測試:
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite(null); // true
isFinite("0"); // true
再看 underscore.js 中的代碼,排除了 NaN 情況:
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
- isNaN, - isBoolean, - isNull, - isUndefined
其他類型判斷函數沒什么特別的代箭,如下墩划。
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
2. jQuery 1.11.2
看看 jQuery 中封裝的類型判斷接口:
$.type(obj)
$.isArray(obj)
$.isFunction(obj)
$.isEmptyObject(obj)
$.isPlainObject(obj)
$.isWindow(obj)
$.isNumeric(value)
其核心代碼如下,也是采用 Object.prototype.toSting
:
var class2type = {};
var toString = class2type.toString;
...
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
...
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
其中 isArray
和 isFunction
是對 type
函數的進一步封裝嗡综。
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
下面繼續(xù)看看其他函數乙帮。
- isEmptyObject
判斷是否為空對象。
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
- isPlainObject
這是 jQuery 中特有的方法极景,判斷一個對象是否為純粹對象(通過 {} 或 new Object() 創(chuàng)建的)察净。
var hasOwn = class2type.hasOwnProperty;
...
isPlainObject: function( obj ) {
var key;
// 不能被轉為true,
// 類型一定要是[object Object]
// 過濾 Dom 節(jié)點和 window 對象
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// 沒有自己的 constructor 屬性的一定為 Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9執(zhí)行上面操作的時候,會報錯盼樟,也返回 false
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// 在枚舉屬性的時候氢卡,自身的屬性會先被枚舉,然后再枚舉繼承的屬性晨缴,如果枚舉的最后一個屬性為自身的译秦,則為 true
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
- isWindow
判斷是否為 window 對象。利用 window = window.window 的屬性击碗。
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
- isNumeric
判斷是否為數字筑悴。
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
}
總結
js 在判斷類型的道路上,曾經有很多的嘗試稍途,每個類庫的判斷方式都不同阁吝,但自從 Object.prototype.toSting
被挖掘出來后,
已經變成了公認的判斷類型方法械拍。
把 jQuery 中的 type
方法抽出來如下:
var typeObj = {} ;
"Boolean Number String Function Array Date RegExp Object Error".split(" ").forEach( function (e, i) {
typeObj[ "[object " + e + "]" ] = e.toLowerCase();
});
function _typeof (obj) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
typeObj[ typeObj.toString.call(obj) ] || "object" :
typeof obj;
}
這樣突勇,在判斷類型的時候装盯,就可以直接用這段代碼了(在沒有判斷函數的時候)。