標籤:cas each err ase regex erro amp 簡單 代碼
Javascript中常見類型對象有:
Boolean, Number, String, Function, Array, Date, RegExp, Object, Error, Symbol等等.
下面提供區分這幾種類型的工具方法,前提是使用javascript,如果項目中使用了jquery或者angularjs等架構,就沒必要自己再寫這樣的工具函數。
第一種:最笨的辦法,一一列舉
function isBoolean(value) {return typeof value === ‘boolean‘;}function isNumber(value) {return typeof value === ‘number‘;}function isString(value) {return typeof value === ‘string‘;}function isFunction(value) {return typeof value === ‘function‘;}var isArray = Array.isArray;function isDate(value) {return toString.call(value) === ‘[object Date]‘;}function isRegExp(value) {return toString.call(value) === ‘[object RegExp]‘;}function isObject(value) {return value !== null && typeof value === ‘object‘;}function isUndefined(value) {return typeof value === ‘undefined‘;}function isDefined(value) {return typeof value !== ‘undefined‘;}function isBlankObject(value) { return value !== null && typeof value === ‘object‘ && !getPrototypeOf(value);}function isFile(obj) {return toString.call(obj) === ‘[object File]‘;}function isFormData(obj) {return toString.call(obj) === ‘[object FormData]‘;}function isBlob(obj) {return toString.call(obj) === ‘[object Blob]‘;}function isWindow(obj) {return obj && obj.window === obj;}
這樣看下來,這些方法其實就是利用 typeof和toString方法,在外面定義一個function而已,也不叫封裝,也沒必要封裝。
使用時,直接用就可以。那如果說在使用時,不知道什麼時候用typeof,什麼時候用toString。
很簡單嘛,直接拷貝上面代碼(壞笑)。要記住這麼多方法名也還挺不容易的,哦?有規律,類別首字母大寫,前面加"is"。
第二種,jQuery式封裝,定義一個統一介面
這種方法相對於上面的方法,就簡單太多了。
想要知道某個對象是什麼類型,調用type()方法。
想要知道某個對象是不是某類型,使用type() ===‘某類型的小寫字串‘,例如:type() ===‘string‘ 或者 type() ===‘array‘
var class2type = {};"Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ).forEach(function(element,index){class2type[ "[object " + element + "]" ] = element.toLowerCase();});function type(obj) {if ( obj == null ) {return obj + "";}return typeof obj === "object" || typeof obj === "function" ?class2type[ toString.call( obj ) ] || "object" :typeof obj;}
javascript 的工具方法 --- 類型判斷