首頁  >  文章  >  web前端  >  Js中如何判斷變數是陣列、函數或物件的程式碼說明

Js中如何判斷變數是陣列、函數或物件的程式碼說明

伊谢尔伦
伊谢尔伦原創
2017-07-18 11:31:001107瀏覽

陣列

     ECMAScript5中Array.isArray是原生的判斷陣列的方法,IE9以上支援。考慮到相容性,在沒有此方法的瀏覽器中,可以使用 Object.prototype.toString.call(obj) === '[object Array]'替代。

var isArray = Array.isArray || function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

JQ的確封裝了一個函數jQuery.inArray( value, array ) 搜尋陣列中指定值並傳回它的索引(如果找不到則傳回-1)。
value要搜尋的值。 array一個數組,透過它來搜尋。

function inArray1(needle,array,bool){  
    if(typeof needle=="string"||typeof needle=="number"){  
        for(var i in array){  
            if(needle===array[i]){  
                if(bool){  
                    return i;  
                }  
                return true;  
            }  
        }  
        return false;  
    }  
}

函數

     最簡單且表現最好的方法就是 typeof obj == 'function'。考慮到某些版本瀏覽器存在的bug,最可靠的辦法是 Object.prototype.toString.call(obj) === '[object Function]'。

var isFunction = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Function]';
}
if(typeof /./ != 'function' && typeof Int8Array != 'object') {
    isFunction = function(obj) {
        return typeof obj == 'function';
    }
}

物件

     在JavaScript中複雜型別是對象,函數也是物件。對上述2者使用typeof,可以分別得到'object'和'function'。另外,也要排除null值的情況,因為typeof null 得到的也是 'object'。

var isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
}

以上是Js中如何判斷變數是陣列、函數或物件的程式碼說明的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn