判斷數據類型的5種方法

1. typeof

  • 可以判斷數據類型,它返回表示數據類型的字符串(返回結果只能包括number,boolean,string,function,object,undefined);
  • 可以使用typeof判斷變量是否存在(如if(typeof a!="undefined"){...});
  • Typeof 運算符的問題是無論引用的對象是什么類型 它都返回object
typeof {} // object
typeof  [1,2] // object
typeof /\s/ //object

2.instanceof

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

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

3.通過Object下的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]

4.根據對象的contructor判斷

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

5.jq中判斷數據類型的方法

jQuery提供了一系列工具方法,用來判斷數據類型,以彌補JavaScript原生的typeof運算符的不足。以下方法對參數進行判斷,返回一個布爾值。
jQuery.isArray();是否為數組
jQuery.isEmptyObject();是否為空對象 (不含可枚舉屬性)。
jQuery.isFunction():是否為函數
jQuery.isNumberic():是否為數字
jQuery.isPlainObject():是否為使用“{}”或“new Object”生成對象,而不是瀏覽器原生提供的對象。
jQuery.isWindow(): 是否為window對象;
jQuery.isXMLDoc(): 判斷一個DOM節點是否處于XML文檔中。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容