javascript 的工具方法 --- 類型判斷

來源:互聯網
上載者:User

標籤: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 的工具方法 --- 類型判斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.