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"// as of jQuery1.9
jQuery.type( /test/ ) "regexp"