JS判斷數(shù)據(jù)類型的五種方法

一、typeof

基本數(shù)據(jù)類型中:Number,String,Boolean,undefined 以及引用數(shù)據(jù)類型中Function ,可以使用typeof檢測數(shù)據(jù)類型,分別返回對應(yīng)的數(shù)據(jù)類型小寫字符。

基本數(shù)據(jù)類型中:null 。引用數(shù)據(jù)類型中的:Array,Object,Date,RegExp。不可以用typeof檢測。都會返回小寫的object

console.log(
    typeof 100, //"number"
    typeof 'abc', //"string"
    typeof false, //"boolean"
    typeof undefined, //"undefined"
    typeof null, //"object"
    typeof [1,2,3], //"object"
    typeof {a:1,b:2,c:3}, //"object"
    typeof function(){console.log('aaa');}, //"function"
    typeof new Date(), //"object"
    typeof /^[a-zA-Z]{5,20}$/, //"object"
    typeof new Error() //"object"
    typeof new Number(100), //'object'
    typeof new String('abc'),// 'string'
    typeof new Boolean(true),//'boolean'
);

二、instanceof

原理 因為A instanceof B 可以判斷A是不是B的實例,返回一個布爾值,由構(gòu)造類型判斷出數(shù)據(jù)類型

arr、date、fn分別是數(shù)組、日期對象、和函數(shù)

console.log(arr instanceof Array ); // true
console.log(date instanceof Date ); // true
console.log(fn instanceof Function ); // true
//注意: instanceof 后面一定要是對象類型,大小寫不能寫錯,該方法試用一些條件選擇或分支

三、通過Object.prototype.toString.call()方法來判斷

Object.prototype.toString.call();
console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]

四、根據(jù)對象的contructor判斷

arr、date、fn分別是數(shù)組、日期對象、和函數(shù)

console.log('數(shù)據(jù)類型判斷' -  constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true

五、jq中判斷數(shù)據(jù)類型的方法

jQuery提供了一系列工具方法,用來判斷數(shù)據(jù)類型,以彌補JavaScript原生的typeof運算符的不足。以下方法對參數(shù)進行判斷,返回一個布爾值。

  • jQuery.isArray();是否為數(shù)組
  • jQuery.isEmptyObject();是否為空對象 (不含可枚舉屬性)。
  • jQuery.isFunction():是否為函數(shù)
  • jQuery.isNumberic():是否為數(shù)字
  • jQuery.isPlainObject():是否為使用“{}”或“new Object”生成對象,而不是瀏覽器原生提供的對象。
  • jQuery.isWindow(): 是否為window對象;
  • jQuery.isXMLDoc(): 判斷一個DOM節(jié)點是否處于XML文檔中。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容