判斷數據類型的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文檔中。


作者:8d2855a6c5d0
鏈接:https://www.jianshu.com/p/967d6db70437
來源:簡書


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM