javascript 資料型別判斷 (常見庫的資料型別判斷原始碼的分析)
JavaScript一共有六種資料型別,分為原始型別(又名基本型別)和物件型別(又名引用型別)
原始型別有五種,分別為number,string,boolean,undefined,null五種。
物件型別常見的有Function,Array,Date,正則
ES6新增Symbol
JavaScript 自己提供的樂行判斷
type
如果不對物件做嚴格區分使用type。
number:
typeof 1; // "number"
string:
typeof 'hello world'; // "string"
boolean:
typeof true; // "boolean"
undefined:
typeof undefined; // "undefined"
null:
typeof null; // "undefined" (特別)
object:
typeof {}; // "object"
Symbol:
typeof Symbol(); // "symbol"
null要單獨處理,就像jQuery中一樣,如果要判斷的物件為null,就直接返回 String(obj)
。
因此,可以寫一個判斷基本型別的方法:
var type = function(obj) {
if(obj === null) return String(obj);
return typeof obj;
}
instanceof
instanceof 是用來明確物件為某種特定型別的方法。
instanceof 的實現使用了原型繼承的L表示左表示式,R表示右表示式,它是用L.proto 是否等於 R.prototype 來判斷物件的型別的。
String:
var str = new String('hello world');
str instanceof String // true
String:
var str = new Number('10');
str instanceof String // true
Datte:
var o = new Date();
o instanceof Date; // true
Array:
var o = new Array();
o instanceof Array; // true
RegExp:
var reg = new RegExp('/^[a-z]$/');
reg instanceof RegExp; // true
Object:
var o = new Object();
o instanceof Object; // true
var o2 = {};
o2 instanceof Object; // true
Function:
var o = function() {};
o instanceof Function; // true
Func(自定義):
function Func() {}
var o = new Func();
o instanceof Func; // true
instanceof 即可以驗證自定義物件,也可以驗證內建物件型別,但有一點我們要注意,那就是他們本身就是物件。
var str = new String('hello world');
str instanceof Object; // true
我們在一開始就說明了instanceof的實現原理,知道instanceof左邊是右邊的例項,所以我們可以用如下程式碼獲取物件的型別名:
obje.__proto__.constructor.name;
因此,我們可以寫一個判斷物件型別的方法如下:
objectType = function(obj) {
if(typeof obj === 'object' || typeof obj === 'function') {
return obj.__proto__.constructor.name;
}
}
上面的方法雖好,但是ie瀏覽器不支援 __proto__
(這個屬性也是我們判斷瀏覽器與非瀏覽器的常用方式)。
下面介紹一個萬能的方法。
Object.prototype.toString.call(obj)
Object.prototype.toString.call('hello world'); // "[object String]"
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(); // "[object Undefined]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.prototype.toString.call(/test/i); // "[object RegExpArray]"
Object.prototype.toString.call(function () {}); // "[object Function]"
獲取資料型別的程式碼如下:
var core_toString = Object.prototype.toString;
var getObjectType = function(obj) () {
return core_toString.call(obj).slice(8, -1);
}
這個方法可以判斷所有的資料型別,也是官方推薦的,但是在實際的開發中,我們使用 typeof
來判斷基本型別,用 Objet.prototype.toString.call(obj)
判斷引用型別。
常見框架和庫的實資料型別判斷
jQuery:
var class2type = {};
var core_toString = Object.prototype.toString;
"Boolean Number String Function Array Date RegExp Object Error".split(' ').forEach(function(name, i) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
var getType = function (obj) {
if (obj == null) {
return String(obj);
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
};
// 測試
getType(function(){}); // "function"
getType([]); // "array"
這裡將jQuery的實現原理抽取出來,用原生js實現。
vue.js
/**
* 判斷是否為基本資料型別
*/
function isPrimitive (value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* 判斷是否為普通物件
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* 獲取原生型別,如: [object Object]
*/
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
/**
* 普通物件
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
/**
* 正則物件
*/
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
angular2:
function isPresent(obj) {
return obj !== undefined && obj !== null;
}
exports.isPresent = isPresent;
function isBlank(obj) {
return obj === undefined || obj === null;
}
exports.isBlank = isBlank;
function isBoolean(obj) {
return typeof obj === "boolean";
}
exports.isBoolean = isBoolean;
function isNumber(obj) {
return typeof obj === "number";
}
exports.isNumber = isNumber;
function isString(obj) {
return typeof obj === "string";
}
exports.isString = isString;
function isFunction(obj) {
return typeof obj === "function";
}
exports.isFunction = isFunction;
function isType(obj) {
return isFunction(obj);
}
exports.isType = isType;
function isStringMap(obj) {
return typeof obj === 'object' && obj !== null;
}
exports.isStringMap = isStringMap;
function isPromise(obj) {
return obj instanceof _global.Promise;
}
exports.isPromise = isPromise;
function isArray(obj) {
return Array.isArray(obj);
}
exports.isArray = isArray;
function isDate(obj) {
return obj instanceof exports.Date && !isNaN(obj.valueOf());
}
exports.isDate = isDate;
我們常見的就是這幾種實現方式,或是這幾種方式的混合(zepto.js)。
JavaScript相關文章github.com