js的數(shù)據(jù)類型: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類型的對(duì)象時(shí)比較方便。
2.判斷已知對(duì)象類型的方法: 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后面一定是對(duì)象類型,大小寫不能寫錯(cuò),必須是Function。
3.根據(jù)對(duì)象的constructor判斷: constructor
console.log(g.constructor === Array );? ? //true
console.log(i.constructor === Date );? ? //true
console.log(h.constructor === Function);? ? //true
注意:constructor在繼承時(shí)會(huì)出錯(cuò)
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.萬(wàn)能: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"