js判斷數據類型的幾種方法

js的數據類型:string,Number,boolean·,Null,undefined,Object,function。

var a = 'string';

var b = 123;

var c = true;

var d = null;

var e = undefined;

var f = {firstname:"Bill", lastname:"Gates"};

var g = [1, 2, 3];

var h = function() { alert(1); };

var i = new Date();

1.typeof

console.log(typeof a);? ? //string

console.log(typeof b);? ? //number

console.log(typeof c);? ? //boolean

console.log(typeof d);? ? //object

console.log(typeof e);? ? //undefined

console.log(typeof f);? ? //object

console.log(typeof g);? ? //object

console.log(typeof h);? ? //function

typeof返回的都是字符串類型

console.log(typeofa =="string") ------------->true

console.log(typeofa ==String) --------------->false

另外typeof可以判斷function的類型;在判斷除Object類型的對象時比較方便。

2.判斷已知對象類型的方法: instanceof

console.log(g instanceof Array);? ? //true

console.log(i instanceof Date);? ? //true

console.log(g instanceof Array);? ? //true

console.log(h instanceof Function);? ? //true

instanceof后面一定是對象類型,大小寫不能寫錯,必須是Function。

3.根據對象的constructor判斷: constructor

console.log(g.constructor === Array );? ? //true

console.log(i.constructor === Date );? ? //true

console.log(h.constructor === Function);? ? //true

注意:constructor在繼承時會出錯

eg:functionA(){};

? ? ? ? functionB(){};

? ? ? ? A.prototype = new B();//A繼承自B

? ? ? ? var aObj = new A();? ? ?

? ? ? ? console.log(aobj.constructor=== B)? ? ? //true

? ? ? ? console.log(aobj.constructor=== A)? ? ? // false

4.利用原型:Object.prototype.toString.call

console.log(Object.prototype.toString.call(a) === ‘[object String]’);? ? //true

console.log(Object.prototype.toString.call(b) === ‘[object Number]’);? ? //true

console.log(Object.prototype.toString.call(g) === ‘[object Array]’);? ? //true

console.log(Object.prototype.toString.call(h) === ‘[object Function]’);? ? //true

console.log(Object.prototype.toString.call(i) === ‘[object Date]’);? ? //true

5.萬能:jQuery.type()

jQuery.type( undefined )? ? "undefined"

jQuery.type()? ? "undefined"

jQuery.type( null )? ? "null"

jQuery.type(true)? ? ? "boolean"

jQuery.type(3)? ? ? ? "number"

jQuery.type("test")? ? ? "string"

jQuery.type(function(){} )? ? ? "function"

jQuery.type( [] )? ? ? "array"

jQuery.type( new Date() )? ? ? "date"

jQuery.type( new Error() )? ? ? ? "error"http:// as of jQuery1.9

jQuery.type( /test/ )? ? ? "regexp"

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

推薦閱讀更多精彩內容