javascript類型判斷

來源:互聯網
上載者:User

標籤:

通常為了快捷我們都會使用 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類型判斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.