来源:https://www.cnblogs.com/dushao/p/5999563.html 1、typeof,返回值是字符串并且首字母小写,可以判断function数据类型,在判断非Object类型的数据时比较方便。
var myString = "he is string";var myNumber = 222;var myArray= [1,2,3];var myDate = new Date();var myObject = {a:1};var myFunction = function(){console.log(111);};console.log(typeof myString) // stringconsole.log(typeof myNumber) // numberconsole.log(typeof myArray) // objectconsole.log(typeof myDate) // objectconsole.log(typeof myObject) // objectconsole.log(typeof myFunction) // functionconsole.log(typeof myNumber == "number") // true
2、instanceof,返回值是布尔并且首字母小写
var myString = "he is string";var myNumber = 222;var myArray= [1,2,3];var myDate = new Date();var myObject = {a:1};var myFunction = function(){console.log(111);};console.log(myString instanceof String) // trueconsole.log(myNumber instanceof Number) // trueconsole.log(myArray instanceof Array) // trueconsole.log(myDate instanceof Date) // trueconsole.log(myObject instanceof Object) // trueconsole.log(myFunction instanceof Function) // true
3、constructor,返回值是对象并且首字母大写
var myString = "he is string";var myNumber = 222;var myArray= [1,2,3];var myDate = new Date();var myObject = {a:1};var myFunction = function(){console.log(111);};console.log(myString.constructor === String) // trueconsole.log(myNumber.constructor === Number) // trueconsole.log(myArray.constructor === Array) // trueconsole.log(myDate.constructor === Date) // trueconsole.log(myObject.constructor === Object) // trueconsole.log(myFunction.constructor === Function) // true
4、prototype,返回值是(数组)字符串。
var myString = "he is string";var myNumber = 222;var myArray= [1,2,3];var myDate = new Date();var myObject = {a:1};var myFunction = function(){console.log(111);};console.log(Object.prototype.toString.call(myString) === "[object String]") // true;console.log(Object.prototype.toString.call(myNumber) === "[object Number]") // true;console.log(Object.prototype.toString.call(myArray) === "[object Array]") // true;console.log(Object.prototype.toString.call(myDate) === "[object Date]") // true;console.log(Object.prototype.toString.call(myObject) === "[object Object]") // true;console.log(Object.prototype.toString.call(myFunction) === "[object Function]") // true;
5、jquery.type()
var myUndefined=undefined;var myNull=null;var myString = "he is string";var myNumber = 222;var myArray= [1,2,3];var myDate = new Date();var myObject = {a:1};var myFunction = function(){console.log(111);};var myError = new Error();var myRegexp = /test/;console.log(jQuery.type(myUndefined) === "undefined");console.log(jQuery.type(myNull) === "null");console.log(jQuery.type(myString) === "string");console.log(jQuery.type(myNumber) === "number");console.log(jQuery.type(myArray ) === "array");console.log(jQuery.type(myDate) === "date");console.log(jQuery.type(myFunction) === "function");console.log(jQuery.type(myError) === "error");console.log(jQuery.type(myRegexp) === "regexp");