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; }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com